fix for external links:
[lhc/web/wiklou.git] / includes / Parser.php
1 <?php
2 /**
3 * File for Parser and related classes
4 *
5 * @package MediaWiki
6 * @subpackage Parser
7 */
8
9 /** */
10 require_once( 'Sanitizer.php' );
11 require_once( 'HttpFunctions.php' );
12
13 /**
14 * Update this version number when the ParserOutput format
15 * changes in an incompatible way, so the parser cache
16 * can automatically discard old data.
17 */
18 define( 'MW_PARSER_VERSION', '1.6.0' );
19
20 /**
21 * Variable substitution O(N^2) attack
22 *
23 * Without countermeasures, it would be possible to attack the parser by saving
24 * a page filled with a large number of inclusions of large pages. The size of
25 * the generated page would be proportional to the square of the input size.
26 * Hence, we limit the number of inclusions of any given page, thus bringing any
27 * attack back to O(N).
28 */
29
30 define( 'MAX_INCLUDE_REPEAT', 100 );
31 define( 'MAX_INCLUDE_SIZE', 1000000 ); // 1 Million
32
33 define( 'RLH_FOR_UPDATE', 1 );
34
35 # Allowed values for $mOutputType
36 define( 'OT_HTML', 1 );
37 define( 'OT_WIKI', 2 );
38 define( 'OT_MSG' , 3 );
39
40 # string parameter for extractTags which will cause it
41 # to strip HTML comments in addition to regular
42 # <XML>-style tags. This should not be anything we
43 # may want to use in wikisyntax
44 define( 'STRIP_COMMENTS', 'HTMLCommentStrip' );
45
46 # Constants needed for external link processing
47 define( 'HTTP_PROTOCOLS', 'http:\/\/|https:\/\/' );
48 # Everything except bracket, space, or control characters
49 define( 'EXT_LINK_URL_CLASS', '[^][<>"\\x00-\\x20\\x7F]' );
50 # Including space
51 define( 'EXT_LINK_TEXT_CLASS', '[^\]\\x00-\\x1F\\x7F]' );
52 define( 'EXT_IMAGE_FNAME_CLASS', '[A-Za-z0-9_.,~%\\-+&;#*?!=()@\\x80-\\xFF]' );
53 define( 'EXT_IMAGE_EXTENSIONS', 'gif|png|jpg|jpeg' );
54 define( 'EXT_LINK_BRACKETED', '/\[(\b(' . wfUrlProtocols() . ')'.EXT_LINK_URL_CLASS.'+)( *)('.EXT_LINK_TEXT_CLASS.'*?)\]/S' );
55 define( 'EXT_IMAGE_REGEX',
56 '/^('.HTTP_PROTOCOLS.')'. # Protocol
57 '('.EXT_LINK_URL_CLASS.'+)\\/'. # Hostname and path
58 '('.EXT_IMAGE_FNAME_CLASS.'+)\\.((?i)'.EXT_IMAGE_EXTENSIONS.')$/S' # Filename
59 );
60
61 /**
62 * PHP Parser
63 *
64 * Processes wiki markup
65 *
66 * <pre>
67 * There are three main entry points into the Parser class:
68 * parse()
69 * produces HTML output
70 * preSaveTransform().
71 * produces altered wiki markup.
72 * transformMsg()
73 * performs brace substitution on MediaWiki messages
74 *
75 * Globals used:
76 * objects: $wgLang
77 *
78 * NOT $wgArticle, $wgUser or $wgTitle. Keep them away!
79 *
80 * settings:
81 * $wgUseTex*, $wgUseDynamicDates*, $wgInterwikiMagic*,
82 * $wgNamespacesWithSubpages, $wgAllowExternalImages*,
83 * $wgLocaltimezone, $wgAllowSpecialInclusion*
84 *
85 * * only within ParserOptions
86 * </pre>
87 *
88 * @package MediaWiki
89 */
90 class Parser
91 {
92 /**#@+
93 * @access private
94 */
95 # Persistent:
96 var $mTagHooks;
97
98 # Cleared with clearState():
99 var $mOutput, $mAutonumber, $mDTopen, $mStripState = array();
100 var $mVariables, $mIncludeCount, $mArgStack, $mLastSection, $mInPre;
101 var $mInterwikiLinkHolders, $mLinkHolders, $mUniqPrefix;
102 var $mTemplates, // cache of already loaded templates, avoids
103 // multiple SQL queries for the same string
104 $mTemplatePath; // stores an unsorted hash of all the templates already loaded
105 // in this path. Used for loop detection.
106
107 # Temporary
108 # These are variables reset at least once per parse regardless of $clearState
109 var $mOptions, // ParserOptions object
110 $mTitle, // Title context, used for self-link rendering and similar things
111 $mOutputType, // Output type, one of the OT_xxx constants
112 $mRevisionId; // ID to display in {{REVISIONID}} tags
113
114 /**#@-*/
115
116 /**
117 * Constructor
118 *
119 * @access public
120 */
121 function Parser() {
122 $this->mTagHooks = array();
123 $this->clearState();
124 }
125
126 /**
127 * Clear Parser state
128 *
129 * @access private
130 */
131 function clearState() {
132 $this->mOutput = new ParserOutput;
133 $this->mAutonumber = 0;
134 $this->mLastSection = '';
135 $this->mDTopen = false;
136 $this->mVariables = false;
137 $this->mIncludeCount = array();
138 $this->mStripState = array();
139 $this->mArgStack = array();
140 $this->mInPre = false;
141 $this->mInterwikiLinkHolders = array(
142 'texts' => array(),
143 'titles' => array()
144 );
145 $this->mLinkHolders = array(
146 'namespaces' => array(),
147 'dbkeys' => array(),
148 'queries' => array(),
149 'texts' => array(),
150 'titles' => array()
151 );
152 $this->mRevisionId = null;
153 $this->mUniqPrefix = 'UNIQ' . Parser::getRandomString();
154
155 # Clear these on every parse, bug 4549
156 $this->mTemplates = array();
157 $this->mTemplatePath = array();
158
159 wfRunHooks( 'ParserClearState', array( &$this ) );
160 }
161
162 /**
163 * Accessor for mUniqPrefix.
164 *
165 * @access public
166 */
167 function UniqPrefix() {
168 return $this->mUniqPrefix;
169 }
170
171 /**
172 * Convert wikitext to HTML
173 * Do not call this function recursively.
174 *
175 * @access private
176 * @param string $text Text we want to parse
177 * @param Title &$title A title object
178 * @param array $options
179 * @param boolean $linestart
180 * @param boolean $clearState
181 * @param int $revid number to pass in {{REVISIONID}}
182 * @return ParserOutput a ParserOutput
183 */
184 function parse( $text, &$title, $options, $linestart = true, $clearState = true, $revid = null ) {
185 /**
186 * First pass--just handle <nowiki> sections, pass the rest off
187 * to internalParse() which does all the real work.
188 */
189
190 global $wgUseTidy, $wgAlwaysUseTidy, $wgContLang;
191 $fname = 'Parser::parse';
192 wfProfileIn( $fname );
193
194 if ( $clearState ) {
195 $this->clearState();
196 }
197
198 $this->mOptions = $options;
199 $this->mTitle =& $title;
200 $this->mRevisionId = $revid;
201 $this->mOutputType = OT_HTML;
202
203 $this->mStripState = NULL;
204
205 //$text = $this->strip( $text, $this->mStripState );
206 // VOODOO MAGIC FIX! Sometimes the above segfaults in PHP5.
207 $x =& $this->mStripState;
208
209 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$x ) );
210 $text = $this->strip( $text, $x );
211 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$x ) );
212
213 # Hook to suspend the parser in this state
214 if ( !wfRunHooks( 'ParserBeforeInternalParse', array( &$this, &$text, &$x ) ) ) {
215 wfProfileOut( $fname );
216 return $text ;
217 }
218
219 $text = $this->internalParse( $text );
220
221 $text = $this->unstrip( $text, $this->mStripState );
222
223 # Clean up special characters, only run once, next-to-last before doBlockLevels
224 $fixtags = array(
225 # french spaces, last one Guillemet-left
226 # only if there is something before the space
227 '/(.) (?=\\?|:|;|!|\\302\\273)/' => '\\1&nbsp;\\2',
228 # french spaces, Guillemet-right
229 '/(\\302\\253) /' => '\\1&nbsp;',
230 '/<center *>(.*)<\\/center *>/i' => '<div class="center">\\1</div>',
231 );
232 $text = preg_replace( array_keys($fixtags), array_values($fixtags), $text );
233
234 # only once and last
235 $text = $this->doBlockLevels( $text, $linestart );
236
237 $this->replaceLinkHolders( $text );
238
239 # the position of the convert() call should not be changed. it
240 # assumes that the links are all replaces and the only thing left
241 # is the <nowiki> mark.
242 $text = $wgContLang->convert($text);
243 $this->mOutput->setTitleText($wgContLang->getParsedTitle());
244
245 $text = $this->unstripNoWiki( $text, $this->mStripState );
246
247 wfRunHooks( 'ParserBeforeTidy', array( &$this, &$text ) );
248
249 $text = Sanitizer::normalizeCharReferences( $text );
250
251 if (($wgUseTidy and $this->mOptions->mTidy) or $wgAlwaysUseTidy) {
252 $text = Parser::tidy($text);
253 }
254
255 wfRunHooks( 'ParserAfterTidy', array( &$this, &$text ) );
256
257 $this->mOutput->setText( $text );
258 wfProfileOut( $fname );
259
260 return $this->mOutput;
261 }
262
263 /**
264 * Get a random string
265 *
266 * @access private
267 * @static
268 */
269 function getRandomString() {
270 return dechex(mt_rand(0, 0x7fffffff)) . dechex(mt_rand(0, 0x7fffffff));
271 }
272
273 /**
274 * Replaces all occurrences of <$tag>content</$tag> in the text
275 * with a random marker and returns the new text. the output parameter
276 * $content will be an associative array filled with data on the form
277 * $unique_marker => content.
278 *
279 * If $content is already set, the additional entries will be appended
280 * If $tag is set to STRIP_COMMENTS, the function will extract
281 * <!-- HTML comments -->
282 *
283 * @access private
284 * @static
285 */
286 function extractTagsAndParams($tag, $text, &$content, &$tags, &$params, $uniq_prefix = ''){
287 $rnd = $uniq_prefix . '-' . $tag . Parser::getRandomString();
288 if ( !$content ) {
289 $content = array( );
290 }
291 $n = 1;
292 $stripped = '';
293
294 if ( !$tags ) {
295 $tags = array( );
296 }
297
298 if ( !$params ) {
299 $params = array( );
300 }
301
302 if( $tag == STRIP_COMMENTS ) {
303 $start = '/<!--()()/';
304 $end = '/-->/';
305 } else {
306 $start = "/<$tag(\\s+[^\\/>]*|\\s*)(\\/?)>/i";
307 $end = "/<\\/$tag\\s*>/i";
308 }
309
310 while ( '' != $text ) {
311 $p = preg_split( $start, $text, 2, PREG_SPLIT_DELIM_CAPTURE );
312 $stripped .= $p[0];
313 if( count( $p ) < 4 ) {
314 break;
315 }
316 $attributes = $p[1];
317 $empty = $p[2];
318 $inside = $p[3];
319
320 $marker = $rnd . sprintf('%08X', $n++);
321 $stripped .= $marker;
322
323 $tags[$marker] = "<$tag$attributes$empty>";
324 $params[$marker] = Sanitizer::decodeTagAttributes( $attributes );
325
326 if ( $empty === '/' ) {
327 // Empty element tag, <tag />
328 $content[$marker] = null;
329 $text = $inside;
330 } else {
331 $q = preg_split( $end, $inside, 2 );
332 $content[$marker] = $q[0];
333 if( count( $q ) < 2 ) {
334 # No end tag -- let it run out to the end of the text.
335 break;
336 } else {
337 $text = $q[1];
338 }
339 }
340 }
341 return $stripped;
342 }
343
344 /**
345 * Wrapper function for extractTagsAndParams
346 * for cases where $tags and $params isn't needed
347 * i.e. where tags will never have params, like <nowiki>
348 *
349 * @access private
350 * @static
351 */
352 function extractTags( $tag, $text, &$content, $uniq_prefix = '' ) {
353 $dummy_tags = array();
354 $dummy_params = array();
355
356 return Parser::extractTagsAndParams( $tag, $text, $content,
357 $dummy_tags, $dummy_params, $uniq_prefix );
358 }
359
360 /**
361 * Strips and renders nowiki, pre, math, hiero
362 * If $render is set, performs necessary rendering operations on plugins
363 * Returns the text, and fills an array with data needed in unstrip()
364 * If the $state is already a valid strip state, it adds to the state
365 *
366 * @param bool $stripcomments when set, HTML comments <!-- like this -->
367 * will be stripped in addition to other tags. This is important
368 * for section editing, where these comments cause confusion when
369 * counting the sections in the wikisource
370 *
371 * @access private
372 */
373 function strip( $text, &$state, $stripcomments = false ) {
374 $render = ($this->mOutputType == OT_HTML);
375 $html_content = array();
376 $nowiki_content = array();
377 $math_content = array();
378 $pre_content = array();
379 $comment_content = array();
380 $ext_content = array();
381 $ext_tags = array();
382 $ext_params = array();
383 $gallery_content = array();
384
385 # Replace any instances of the placeholders
386 $uniq_prefix = $this->mUniqPrefix;
387 #$text = str_replace( $uniq_prefix, wfHtmlEscapeFirst( $uniq_prefix ), $text );
388
389 # html
390 global $wgRawHtml;
391 if( $wgRawHtml ) {
392 $text = Parser::extractTags('html', $text, $html_content, $uniq_prefix);
393 foreach( $html_content as $marker => $content ) {
394 if ($render ) {
395 # Raw and unchecked for validity.
396 $html_content[$marker] = $content;
397 } else {
398 $html_content[$marker] = '<html>'.$content.'</html>';
399 }
400 }
401 }
402
403 # nowiki
404 $text = Parser::extractTags('nowiki', $text, $nowiki_content, $uniq_prefix);
405 foreach( $nowiki_content as $marker => $content ) {
406 if( $render ){
407 $nowiki_content[$marker] = wfEscapeHTMLTagsOnly( $content );
408 } else {
409 $nowiki_content[$marker] = '<nowiki>'.$content.'</nowiki>';
410 }
411 }
412
413 # math
414 if( $this->mOptions->getUseTeX() ) {
415 $text = Parser::extractTags('math', $text, $math_content, $uniq_prefix);
416 foreach( $math_content as $marker => $content ){
417 if( $render ) {
418 $math_content[$marker] = renderMath( $content );
419 } else {
420 $math_content[$marker] = '<math>'.$content.'</math>';
421 }
422 }
423 }
424
425 # pre
426 $text = Parser::extractTags('pre', $text, $pre_content, $uniq_prefix);
427 foreach( $pre_content as $marker => $content ){
428 if( $render ){
429 $pre_content[$marker] = '<pre>' . wfEscapeHTMLTagsOnly( $content ) . '</pre>';
430 } else {
431 $pre_content[$marker] = '<pre>'.$content.'</pre>';
432 }
433 }
434
435 # gallery
436 $text = Parser::extractTags('gallery', $text, $gallery_content, $uniq_prefix);
437 foreach( $gallery_content as $marker => $content ) {
438 require_once( 'ImageGallery.php' );
439 if ( $render ) {
440 $gallery_content[$marker] = $this->renderImageGallery( $content );
441 } else {
442 $gallery_content[$marker] = '<gallery>'.$content.'</gallery>';
443 }
444 }
445
446 # Comments
447 if($stripcomments) {
448 $text = Parser::extractTags(STRIP_COMMENTS, $text, $comment_content, $uniq_prefix);
449 foreach( $comment_content as $marker => $content ){
450 $comment_content[$marker] = '<!--'.$content.'-->';
451 }
452 }
453
454 # Extensions
455 foreach ( $this->mTagHooks as $tag => $callback ) {
456 $ext_content[$tag] = array();
457 $text = Parser::extractTagsAndParams( $tag, $text, $ext_content[$tag],
458 $ext_tags[$tag], $ext_params[$tag], $uniq_prefix );
459 foreach( $ext_content[$tag] as $marker => $content ) {
460 $full_tag = $ext_tags[$tag][$marker];
461 $params = $ext_params[$tag][$marker];
462 if ( $render )
463 $ext_content[$tag][$marker] = call_user_func_array( $callback, array( $content, $params, &$this ) );
464 else {
465 if ( is_null( $content ) ) {
466 // Empty element tag
467 $ext_content[$tag][$marker] = $full_tag;
468 } else {
469 $ext_content[$tag][$marker] = "$full_tag$content</$tag>";
470 }
471 }
472 }
473 }
474
475 # Merge state with the pre-existing state, if there is one
476 if ( $state ) {
477 $state['html'] = $state['html'] + $html_content;
478 $state['nowiki'] = $state['nowiki'] + $nowiki_content;
479 $state['math'] = $state['math'] + $math_content;
480 $state['pre'] = $state['pre'] + $pre_content;
481 $state['gallery'] = $state['gallery'] + $gallery_content;
482 $state['comment'] = $state['comment'] + $comment_content;
483
484 foreach( $ext_content as $tag => $array ) {
485 if ( array_key_exists( $tag, $state ) ) {
486 $state[$tag] = $state[$tag] + $array;
487 }
488 }
489 } else {
490 $state = array(
491 'html' => $html_content,
492 'nowiki' => $nowiki_content,
493 'math' => $math_content,
494 'pre' => $pre_content,
495 'gallery' => $gallery_content,
496 'comment' => $comment_content,
497 ) + $ext_content;
498 }
499 return $text;
500 }
501
502 /**
503 * restores pre, math, and hiero removed by strip()
504 *
505 * always call unstripNoWiki() after this one
506 * @access private
507 */
508 function unstrip( $text, &$state ) {
509 if ( !is_array( $state ) ) {
510 return $text;
511 }
512
513 # Must expand in reverse order, otherwise nested tags will be corrupted
514 foreach( array_reverse( $state, true ) as $tag => $contentDict ) {
515 if( $tag != 'nowiki' && $tag != 'html' ) {
516 foreach( array_reverse( $contentDict, true ) as $uniq => $content ) {
517 $text = str_replace( $uniq, $content, $text );
518 }
519 }
520 }
521
522 return $text;
523 }
524
525 /**
526 * always call this after unstrip() to preserve the order
527 *
528 * @access private
529 */
530 function unstripNoWiki( $text, &$state ) {
531 if ( !is_array( $state ) ) {
532 return $text;
533 }
534
535 # Must expand in reverse order, otherwise nested tags will be corrupted
536 for ( $content = end($state['nowiki']); $content !== false; $content = prev( $state['nowiki'] ) ) {
537 $text = str_replace( key( $state['nowiki'] ), $content, $text );
538 }
539
540 global $wgRawHtml;
541 if ($wgRawHtml) {
542 for ( $content = end($state['html']); $content !== false; $content = prev( $state['html'] ) ) {
543 $text = str_replace( key( $state['html'] ), $content, $text );
544 }
545 }
546
547 return $text;
548 }
549
550 /**
551 * Add an item to the strip state
552 * Returns the unique tag which must be inserted into the stripped text
553 * The tag will be replaced with the original text in unstrip()
554 *
555 * @access private
556 */
557 function insertStripItem( $text, &$state ) {
558 $rnd = $this->mUniqPrefix . '-item' . Parser::getRandomString();
559 if ( !$state ) {
560 $state = array(
561 'html' => array(),
562 'nowiki' => array(),
563 'math' => array(),
564 'pre' => array(),
565 'comment' => array(),
566 'gallery' => array(),
567 );
568 }
569 $state['item'][$rnd] = $text;
570 return $rnd;
571 }
572
573 /**
574 * Interface with html tidy, used if $wgUseTidy = true.
575 * If tidy isn't able to correct the markup, the original will be
576 * returned in all its glory with a warning comment appended.
577 *
578 * Either the external tidy program or the in-process tidy extension
579 * will be used depending on availability. Override the default
580 * $wgTidyInternal setting to disable the internal if it's not working.
581 *
582 * @param string $text Hideous HTML input
583 * @return string Corrected HTML output
584 * @access public
585 * @static
586 */
587 function tidy( $text ) {
588 global $wgTidyInternal;
589 $wrappedtext = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"'.
590 ' "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html>'.
591 '<head><title>test</title></head><body>'.$text.'</body></html>';
592 if( $wgTidyInternal ) {
593 $correctedtext = Parser::internalTidy( $wrappedtext );
594 } else {
595 $correctedtext = Parser::externalTidy( $wrappedtext );
596 }
597 if( is_null( $correctedtext ) ) {
598 wfDebug( "Tidy error detected!\n" );
599 return $text . "\n<!-- Tidy found serious XHTML errors -->\n";
600 }
601 return $correctedtext;
602 }
603
604 /**
605 * Spawn an external HTML tidy process and get corrected markup back from it.
606 *
607 * @access private
608 * @static
609 */
610 function externalTidy( $text ) {
611 global $wgTidyConf, $wgTidyBin, $wgTidyOpts;
612 $fname = 'Parser::externalTidy';
613 wfProfileIn( $fname );
614
615 $cleansource = '';
616 $opts = ' -utf8';
617
618 $descriptorspec = array(
619 0 => array('pipe', 'r'),
620 1 => array('pipe', 'w'),
621 2 => array('file', '/dev/null', 'a')
622 );
623 $pipes = array();
624 $process = proc_open("$wgTidyBin -config $wgTidyConf $wgTidyOpts$opts", $descriptorspec, $pipes);
625 if (is_resource($process)) {
626 // Theoretically, this style of communication could cause a deadlock
627 // here. If the stdout buffer fills up, then writes to stdin could
628 // block. This doesn't appear to happen with tidy, because tidy only
629 // writes to stdout after it's finished reading from stdin. Search
630 // for tidyParseStdin and tidySaveStdout in console/tidy.c
631 fwrite($pipes[0], $text);
632 fclose($pipes[0]);
633 while (!feof($pipes[1])) {
634 $cleansource .= fgets($pipes[1], 1024);
635 }
636 fclose($pipes[1]);
637 proc_close($process);
638 }
639
640 wfProfileOut( $fname );
641
642 if( $cleansource == '' && $text != '') {
643 // Some kind of error happened, so we couldn't get the corrected text.
644 // Just give up; we'll use the source text and append a warning.
645 return null;
646 } else {
647 return $cleansource;
648 }
649 }
650
651 /**
652 * Use the HTML tidy PECL extension to use the tidy library in-process,
653 * saving the overhead of spawning a new process. Currently written to
654 * the PHP 4.3.x version of the extension, may not work on PHP 5.
655 *
656 * 'pear install tidy' should be able to compile the extension module.
657 *
658 * @access private
659 * @static
660 */
661 function internalTidy( $text ) {
662 global $wgTidyConf;
663 $fname = 'Parser::internalTidy';
664 wfProfileIn( $fname );
665
666 tidy_load_config( $wgTidyConf );
667 tidy_set_encoding( 'utf8' );
668 tidy_parse_string( $text );
669 tidy_clean_repair();
670 if( tidy_get_status() == 2 ) {
671 // 2 is magic number for fatal error
672 // http://www.php.net/manual/en/function.tidy-get-status.php
673 $cleansource = null;
674 } else {
675 $cleansource = tidy_get_output();
676 }
677 wfProfileOut( $fname );
678 return $cleansource;
679 }
680
681 /**
682 * parse the wiki syntax used to render tables
683 *
684 * @access private
685 */
686 function doTableStuff ( $t ) {
687 $fname = 'Parser::doTableStuff';
688 wfProfileIn( $fname );
689
690 $t = explode ( "\n" , $t ) ;
691 $td = array () ; # Is currently a td tag open?
692 $ltd = array () ; # Was it TD or TH?
693 $tr = array () ; # Is currently a tr tag open?
694 $ltr = array () ; # tr attributes
695 $has_opened_tr = array(); # Did this table open a <tr> element?
696 $indent_level = 0; # indent level of the table
697 foreach ( $t AS $k => $x )
698 {
699 $x = trim ( $x ) ;
700 $fc = substr ( $x , 0 , 1 ) ;
701 if ( preg_match( '/^(:*)\{\|(.*)$/', $x, $matches ) ) {
702 $indent_level = strlen( $matches[1] );
703
704 $attributes = $this->unstripForHTML( $matches[2] );
705
706 $t[$k] = str_repeat( '<dl><dd>', $indent_level ) .
707 '<table' . Sanitizer::fixTagAttributes ( $attributes, 'table' ) . '>' ;
708 array_push ( $td , false ) ;
709 array_push ( $ltd , '' ) ;
710 array_push ( $tr , false ) ;
711 array_push ( $ltr , '' ) ;
712 array_push ( $has_opened_tr, false );
713 }
714 else if ( count ( $td ) == 0 ) { } # Don't do any of the following
715 else if ( '|}' == substr ( $x , 0 , 2 ) ) {
716 $z = "</table>" . substr ( $x , 2);
717 $l = array_pop ( $ltd ) ;
718 if ( !array_pop ( $has_opened_tr ) ) $z = "<tr><td></td></tr>" . $z ;
719 if ( array_pop ( $tr ) ) $z = '</tr>' . $z ;
720 if ( array_pop ( $td ) ) $z = '</'.$l.'>' . $z ;
721 array_pop ( $ltr ) ;
722 $t[$k] = $z . str_repeat( '</dd></dl>', $indent_level );
723 }
724 else if ( '|-' == substr ( $x , 0 , 2 ) ) { # Allows for |---------------
725 $x = substr ( $x , 1 ) ;
726 while ( $x != '' && substr ( $x , 0 , 1 ) == '-' ) $x = substr ( $x , 1 ) ;
727 $z = '' ;
728 $l = array_pop ( $ltd ) ;
729 array_pop ( $has_opened_tr );
730 array_push ( $has_opened_tr , true ) ;
731 if ( array_pop ( $tr ) ) $z = '</tr>' . $z ;
732 if ( array_pop ( $td ) ) $z = '</'.$l.'>' . $z ;
733 array_pop ( $ltr ) ;
734 $t[$k] = $z ;
735 array_push ( $tr , false ) ;
736 array_push ( $td , false ) ;
737 array_push ( $ltd , '' ) ;
738 $attributes = $this->unstripForHTML( $x );
739 array_push ( $ltr , Sanitizer::fixTagAttributes ( $attributes, 'tr' ) ) ;
740 }
741 else if ( '|' == $fc || '!' == $fc || '|+' == substr ( $x , 0 , 2 ) ) { # Caption
742 # $x is a table row
743 if ( '|+' == substr ( $x , 0 , 2 ) ) {
744 $fc = '+' ;
745 $x = substr ( $x , 1 ) ;
746 }
747 $after = substr ( $x , 1 ) ;
748 if ( $fc == '!' ) $after = str_replace ( '!!' , '||' , $after ) ;
749 $after = explode ( '||' , $after ) ;
750 $t[$k] = '' ;
751
752 # Loop through each table cell
753 foreach ( $after AS $theline )
754 {
755 $z = '' ;
756 if ( $fc != '+' )
757 {
758 $tra = array_pop ( $ltr ) ;
759 if ( !array_pop ( $tr ) ) $z = '<tr'.$tra.">\n" ;
760 array_push ( $tr , true ) ;
761 array_push ( $ltr , '' ) ;
762 array_pop ( $has_opened_tr );
763 array_push ( $has_opened_tr , true ) ;
764 }
765
766 $l = array_pop ( $ltd ) ;
767 if ( array_pop ( $td ) ) $z = '</'.$l.'>' . $z ;
768 if ( $fc == '|' ) $l = 'td' ;
769 else if ( $fc == '!' ) $l = 'th' ;
770 else if ( $fc == '+' ) $l = 'caption' ;
771 else $l = '' ;
772 array_push ( $ltd , $l ) ;
773
774 # Cell parameters
775 $y = explode ( '|' , $theline , 2 ) ;
776 # Note that a '|' inside an invalid link should not
777 # be mistaken as delimiting cell parameters
778 if ( strpos( $y[0], '[[' ) !== false ) {
779 $y = array ($theline);
780 }
781 if ( count ( $y ) == 1 )
782 $y = "{$z}<{$l}>{$y[0]}" ;
783 else {
784 $attributes = $this->unstripForHTML( $y[0] );
785 $y = "{$z}<{$l}".Sanitizer::fixTagAttributes($attributes, $l).">{$y[1]}" ;
786 }
787 $t[$k] .= $y ;
788 array_push ( $td , true ) ;
789 }
790 }
791 }
792
793 # Closing open td, tr && table
794 while ( count ( $td ) > 0 )
795 {
796 $l = array_pop ( $ltd ) ;
797 if ( array_pop ( $td ) ) $t[] = '</td>' ;
798 if ( array_pop ( $tr ) ) $t[] = '</tr>' ;
799 if ( !array_pop ( $has_opened_tr ) ) $t[] = "<tr><td></td></tr>" ;
800 $t[] = '</table>' ;
801 }
802
803 $t = implode ( "\n" , $t ) ;
804 wfProfileOut( $fname );
805 return $t ;
806 }
807
808 /**
809 * Helper function for parse() that transforms wiki markup into
810 * HTML. Only called for $mOutputType == OT_HTML.
811 *
812 * @access private
813 */
814 function internalParse( $text ) {
815 global $wgContLang;
816 $args = array();
817 $isMain = true;
818 $fname = 'Parser::internalParse';
819 wfProfileIn( $fname );
820
821 # Remove <noinclude> tags and <includeonly> sections
822 $text = strtr( $text, array( '<onlyinclude>' => '' , '</onlyinclude>' => '' ) );
823 $text = strtr( $text, array( '<noinclude>' => '', '</noinclude>' => '') );
824 $text = preg_replace( '/<includeonly>.*?<\/includeonly>/s', '', $text );
825
826 $text = Sanitizer::removeHTMLtags( $text, array( &$this, 'attributeStripCallback' ) );
827 $text = $this->replaceVariables( $text, $args );
828
829 $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text );
830
831 $text = $this->doHeadings( $text );
832 if($this->mOptions->getUseDynamicDates()) {
833 $df =& DateFormatter::getInstance();
834 $text = $df->reformat( $this->mOptions->getDateFormat(), $text );
835 }
836 $text = $this->doAllQuotes( $text );
837 $text = $this->replaceInternalLinks( $text );
838 $text = $this->replaceExternalLinks( $text );
839
840 # replaceInternalLinks may sometimes leave behind
841 # absolute URLs, which have to be masked to hide them from replaceExternalLinks
842 $text = str_replace($this->mUniqPrefix."NOPARSE", "", $text);
843
844 $text = $this->doMagicLinks( $text );
845 $text = $this->doTableStuff( $text );
846 $text = $this->formatHeadings( $text, $isMain );
847
848 wfProfileOut( $fname );
849 return $text;
850 }
851
852 /**
853 * Replace special strings like "ISBN xxx" and "RFC xxx" with
854 * magic external links.
855 *
856 * @access private
857 */
858 function &doMagicLinks( &$text ) {
859 $text = $this->magicISBN( $text );
860 $text = $this->magicRFC( $text, 'RFC ', 'rfcurl' );
861 $text = $this->magicRFC( $text, 'PMID ', 'pubmedurl' );
862 return $text;
863 }
864
865 /**
866 * Parse headers and return html
867 *
868 * @access private
869 */
870 function doHeadings( $text ) {
871 $fname = 'Parser::doHeadings';
872 wfProfileIn( $fname );
873 for ( $i = 6; $i >= 1; --$i ) {
874 $h = str_repeat( '=', $i );
875 $text = preg_replace( "/^{$h}(.+){$h}(\\s|$)/m",
876 "<h{$i}>\\1</h{$i}>\\2", $text );
877 }
878 wfProfileOut( $fname );
879 return $text;
880 }
881
882 /**
883 * Replace single quotes with HTML markup
884 * @access private
885 * @return string the altered text
886 */
887 function doAllQuotes( $text ) {
888 $fname = 'Parser::doAllQuotes';
889 wfProfileIn( $fname );
890 $outtext = '';
891 $lines = explode( "\n", $text );
892 foreach ( $lines as $line ) {
893 $outtext .= $this->doQuotes ( $line ) . "\n";
894 }
895 $outtext = substr($outtext, 0,-1);
896 wfProfileOut( $fname );
897 return $outtext;
898 }
899
900 /**
901 * Helper function for doAllQuotes()
902 * @access private
903 */
904 function doQuotes( $text ) {
905 $arr = preg_split( "/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE );
906 if ( count( $arr ) == 1 )
907 return $text;
908 else
909 {
910 # First, do some preliminary work. This may shift some apostrophes from
911 # being mark-up to being text. It also counts the number of occurrences
912 # of bold and italics mark-ups.
913 $i = 0;
914 $numbold = 0;
915 $numitalics = 0;
916 foreach ( $arr as $r )
917 {
918 if ( ( $i % 2 ) == 1 )
919 {
920 # If there are ever four apostrophes, assume the first is supposed to
921 # be text, and the remaining three constitute mark-up for bold text.
922 if ( strlen( $arr[$i] ) == 4 )
923 {
924 $arr[$i-1] .= "'";
925 $arr[$i] = "'''";
926 }
927 # If there are more than 5 apostrophes in a row, assume they're all
928 # text except for the last 5.
929 else if ( strlen( $arr[$i] ) > 5 )
930 {
931 $arr[$i-1] .= str_repeat( "'", strlen( $arr[$i] ) - 5 );
932 $arr[$i] = "'''''";
933 }
934 # Count the number of occurrences of bold and italics mark-ups.
935 # We are not counting sequences of five apostrophes.
936 if ( strlen( $arr[$i] ) == 2 ) $numitalics++; else
937 if ( strlen( $arr[$i] ) == 3 ) $numbold++; else
938 if ( strlen( $arr[$i] ) == 5 ) { $numitalics++; $numbold++; }
939 }
940 $i++;
941 }
942
943 # If there is an odd number of both bold and italics, it is likely
944 # that one of the bold ones was meant to be an apostrophe followed
945 # by italics. Which one we cannot know for certain, but it is more
946 # likely to be one that has a single-letter word before it.
947 if ( ( $numbold % 2 == 1 ) && ( $numitalics % 2 == 1 ) )
948 {
949 $i = 0;
950 $firstsingleletterword = -1;
951 $firstmultiletterword = -1;
952 $firstspace = -1;
953 foreach ( $arr as $r )
954 {
955 if ( ( $i % 2 == 1 ) and ( strlen( $r ) == 3 ) )
956 {
957 $x1 = substr ($arr[$i-1], -1);
958 $x2 = substr ($arr[$i-1], -2, 1);
959 if ($x1 == ' ') {
960 if ($firstspace == -1) $firstspace = $i;
961 } else if ($x2 == ' ') {
962 if ($firstsingleletterword == -1) $firstsingleletterword = $i;
963 } else {
964 if ($firstmultiletterword == -1) $firstmultiletterword = $i;
965 }
966 }
967 $i++;
968 }
969
970 # If there is a single-letter word, use it!
971 if ($firstsingleletterword > -1)
972 {
973 $arr [ $firstsingleletterword ] = "''";
974 $arr [ $firstsingleletterword-1 ] .= "'";
975 }
976 # If not, but there's a multi-letter word, use that one.
977 else if ($firstmultiletterword > -1)
978 {
979 $arr [ $firstmultiletterword ] = "''";
980 $arr [ $firstmultiletterword-1 ] .= "'";
981 }
982 # ... otherwise use the first one that has neither.
983 # (notice that it is possible for all three to be -1 if, for example,
984 # there is only one pentuple-apostrophe in the line)
985 else if ($firstspace > -1)
986 {
987 $arr [ $firstspace ] = "''";
988 $arr [ $firstspace-1 ] .= "'";
989 }
990 }
991
992 # Now let's actually convert our apostrophic mush to HTML!
993 $output = '';
994 $buffer = '';
995 $state = '';
996 $i = 0;
997 foreach ($arr as $r)
998 {
999 if (($i % 2) == 0)
1000 {
1001 if ($state == 'both')
1002 $buffer .= $r;
1003 else
1004 $output .= $r;
1005 }
1006 else
1007 {
1008 if (strlen ($r) == 2)
1009 {
1010 if ($state == 'i')
1011 { $output .= '</i>'; $state = ''; }
1012 else if ($state == 'bi')
1013 { $output .= '</i>'; $state = 'b'; }
1014 else if ($state == 'ib')
1015 { $output .= '</b></i><b>'; $state = 'b'; }
1016 else if ($state == 'both')
1017 { $output .= '<b><i>'.$buffer.'</i>'; $state = 'b'; }
1018 else # $state can be 'b' or ''
1019 { $output .= '<i>'; $state .= 'i'; }
1020 }
1021 else if (strlen ($r) == 3)
1022 {
1023 if ($state == 'b')
1024 { $output .= '</b>'; $state = ''; }
1025 else if ($state == 'bi')
1026 { $output .= '</i></b><i>'; $state = 'i'; }
1027 else if ($state == 'ib')
1028 { $output .= '</b>'; $state = 'i'; }
1029 else if ($state == 'both')
1030 { $output .= '<i><b>'.$buffer.'</b>'; $state = 'i'; }
1031 else # $state can be 'i' or ''
1032 { $output .= '<b>'; $state .= 'b'; }
1033 }
1034 else if (strlen ($r) == 5)
1035 {
1036 if ($state == 'b')
1037 { $output .= '</b><i>'; $state = 'i'; }
1038 else if ($state == 'i')
1039 { $output .= '</i><b>'; $state = 'b'; }
1040 else if ($state == 'bi')
1041 { $output .= '</i></b>'; $state = ''; }
1042 else if ($state == 'ib')
1043 { $output .= '</b></i>'; $state = ''; }
1044 else if ($state == 'both')
1045 { $output .= '<i><b>'.$buffer.'</b></i>'; $state = ''; }
1046 else # ($state == '')
1047 { $buffer = ''; $state = 'both'; }
1048 }
1049 }
1050 $i++;
1051 }
1052 # Now close all remaining tags. Notice that the order is important.
1053 if ($state == 'b' || $state == 'ib')
1054 $output .= '</b>';
1055 if ($state == 'i' || $state == 'bi' || $state == 'ib')
1056 $output .= '</i>';
1057 if ($state == 'bi')
1058 $output .= '</b>';
1059 if ($state == 'both')
1060 $output .= '<b><i>'.$buffer.'</i></b>';
1061 return $output;
1062 }
1063 }
1064
1065 /**
1066 * Replace external links
1067 *
1068 * Note: this is all very hackish and the order of execution matters a lot.
1069 * Make sure to run maintenance/parserTests.php if you change this code.
1070 *
1071 * @access private
1072 */
1073 function replaceExternalLinks( $text ) {
1074 global $wgContLang;
1075 $fname = 'Parser::replaceExternalLinks';
1076 wfProfileIn( $fname );
1077
1078 $sk =& $this->mOptions->getSkin();
1079
1080 $bits = preg_split( EXT_LINK_BRACKETED, $text, -1, PREG_SPLIT_DELIM_CAPTURE );
1081
1082 $s = $this->replaceFreeExternalLinks( array_shift( $bits ) );
1083
1084 $i = 0;
1085 while ( $i<count( $bits ) ) {
1086 $url = $bits[$i++];
1087 $protocol = $bits[$i++];
1088 $spaces = $bits[$i++];
1089 $text = $bits[$i++];
1090 $trail = $bits[$i++];
1091
1092 # The characters '<' and '>' (which were escaped by
1093 # removeHTMLtags()) should not be included in
1094 # URLs, per RFC 2396.
1095 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE)) {
1096 $text = substr($url, $m2[0][1]) . ' ' . $text;
1097 $url = substr($url, 0, $m2[0][1]);
1098 }
1099
1100 # If the link text is an image URL, replace it with an <img> tag
1101 # This happened by accident in the original parser, but some people used it extensively
1102 $img = $this->maybeMakeExternalImage( $text );
1103 if ( $img !== false ) {
1104 $text = $img;
1105 }
1106
1107 $dtrail = '';
1108
1109 # Set linktype for CSS - if URL==text, link is essentially free
1110 $linktype = ($text == $url) ? 'free' : 'text';
1111
1112 # No link text, e.g. [http://domain.tld/some.link]
1113 if ( $text == '' ) {
1114 # Autonumber if allowed
1115 if ( strpos( HTTP_PROTOCOLS, str_replace('/','\/', $protocol) ) !== false ) {
1116 $text = '[' . ++$this->mAutonumber . ']';
1117 $linktype = 'autonumber';
1118 } else {
1119 # Otherwise just use the URL
1120 $text = htmlspecialchars( $url );
1121 $linktype = 'free';
1122 }
1123 } else {
1124 # Have link text, e.g. [http://domain.tld/some.link text]s
1125 # Check for trail
1126 list( $dtrail, $trail ) = Linker::splitTrail( $trail );
1127 }
1128
1129 $text = $wgContLang->markNoConversion($text);
1130
1131 # Replace &amp; from obsolete syntax with &.
1132 # All HTML entities will be escaped by makeExternalLink()
1133 $url = str_replace( '&amp;', '&', $url );
1134 # Replace unnecessary URL escape codes with the referenced character
1135 # This prevents spammers from hiding links from the filters
1136 $url = Parser::replaceUnusualEscapes( $url );
1137
1138 # Process the trail (i.e. everything after this link up until start of the next link),
1139 # replacing any non-bracketed links
1140 $trail = $this->replaceFreeExternalLinks( $trail );
1141
1142 # Use the encoded URL
1143 # This means that users can paste URLs directly into the text
1144 # Funny characters like &ouml; aren't valid in URLs anyway
1145 # This was changed in August 2004
1146 if ( strlen ( $spaces ) < 2 ) {
1147 # Normal case
1148 $s .= $sk->makeExternalLink( $url, $text, false, $linktype ) . $dtrail . $trail;
1149 } else {
1150 # Fix for [url text] (notice the two blanks)
1151 $s .= '[' . $sk->makeExternalLink( $url, $url, false, "free" ) . $spaces . $text . ']' . $dtrail . $trail;
1152 }
1153
1154 # Register link in the output object
1155 $this->mOutput->addExternalLink( $url );
1156 }
1157
1158 wfProfileOut( $fname );
1159 return $s;
1160 }
1161
1162 /**
1163 * Replace anything that looks like a URL with a link
1164 * @access private
1165 */
1166 function replaceFreeExternalLinks( $text ) {
1167 global $wgContLang;
1168 $fname = 'Parser::replaceFreeExternalLinks';
1169 wfProfileIn( $fname );
1170
1171 $bits = preg_split( '/(\b(?:' . wfUrlProtocols() . '))/S', $text, -1, PREG_SPLIT_DELIM_CAPTURE );
1172 $s = array_shift( $bits );
1173 $i = 0;
1174
1175 $sk =& $this->mOptions->getSkin();
1176
1177 while ( $i < count( $bits ) ){
1178 $protocol = $bits[$i++];
1179 $remainder = $bits[$i++];
1180
1181 if ( preg_match( '/^('.EXT_LINK_URL_CLASS.'+)(.*)$/s', $remainder, $m ) ) {
1182 # Found some characters after the protocol that look promising
1183 $url = $protocol . $m[1];
1184 $trail = $m[2];
1185
1186 # The characters '<' and '>' (which were escaped by
1187 # removeHTMLtags()) should not be included in
1188 # URLs, per RFC 2396.
1189 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE)) {
1190 $trail = substr($url, $m2[0][1]) . $trail;
1191 $url = substr($url, 0, $m2[0][1]);
1192 }
1193
1194 # Move trailing punctuation to $trail
1195 $sep = ',;\.:!?';
1196 # If there is no left bracket, then consider right brackets fair game too
1197 if ( strpos( $url, '(' ) === false ) {
1198 $sep .= ')';
1199 }
1200
1201 $numSepChars = strspn( strrev( $url ), $sep );
1202 if ( $numSepChars ) {
1203 $trail = substr( $url, -$numSepChars ) . $trail;
1204 $url = substr( $url, 0, -$numSepChars );
1205 }
1206
1207 # Replace &amp; from obsolete syntax with &.
1208 # All HTML entities will be escaped by makeExternalLink()
1209 # or maybeMakeExternalImage()
1210 $url = str_replace( '&amp;', '&', $url );
1211 # Replace unnecessary URL escape codes with their equivalent characters
1212 $url = Parser::replaceUnusualEscapes( $url );
1213
1214 # Is this an external image?
1215 $text = $this->maybeMakeExternalImage( $url );
1216 if ( $text === false ) {
1217 # Not an image, make a link
1218 $text = $sk->makeExternalLink( $url, $wgContLang->markNoConversion($url), true, 'free' );
1219 # Register it in the output object
1220 $this->mOutput->addExternalLink( $url );
1221 }
1222 $s .= $text . $trail;
1223 } else {
1224 $s .= $protocol . $remainder;
1225 }
1226 }
1227 wfProfileOut( $fname );
1228 return $s;
1229 }
1230
1231 /**
1232 * Replace unusual URL escape codes with their equivalent characters
1233 * @param string
1234 * @return string
1235 * @static
1236 */
1237 function replaceUnusualEscapes( $url ) {
1238 return preg_replace_callback( '/%[0-9A-Fa-f]{2}/',
1239 array( 'Parser', 'replaceUnusualEscapesCallback' ), $url );
1240 }
1241
1242 /**
1243 * Callback function used in replaceUnusualEscapes().
1244 * Replaces unusual URL escape codes with their equivalent character
1245 * @static
1246 * @access private
1247 */
1248 function replaceUnusualEscapesCallback( $matches ) {
1249 $char = urldecode( $matches[0] );
1250 $ord = ord( $char );
1251 // Is it an unsafe or HTTP reserved character according to RFC 1738?
1252 if ( $ord > 32 && $ord < 127 && strpos( '<>"#{}|\^~[]`;/?', $char ) === false ) {
1253 // No, shouldn't be escaped
1254 return $char;
1255 } else {
1256 // Yes, leave it escaped
1257 return $matches[0];
1258 }
1259 }
1260
1261 /**
1262 * make an image if it's allowed, either through the global
1263 * option or through the exception
1264 * @access private
1265 */
1266 function maybeMakeExternalImage( $url ) {
1267 $sk =& $this->mOptions->getSkin();
1268 $imagesfrom = $this->mOptions->getAllowExternalImagesFrom();
1269 $imagesexception = !empty($imagesfrom);
1270 $text = false;
1271 if ( $this->mOptions->getAllowExternalImages()
1272 || ( $imagesexception && strpos( $url, $imagesfrom ) === 0 ) ) {
1273 if ( preg_match( EXT_IMAGE_REGEX, $url ) ) {
1274 # Image found
1275 $text = $sk->makeExternalImage( htmlspecialchars( $url ) );
1276 }
1277 }
1278 return $text;
1279 }
1280
1281 /**
1282 * Process [[ ]] wikilinks
1283 *
1284 * @access private
1285 */
1286 function replaceInternalLinks( $s ) {
1287 global $wgContLang;
1288 static $fname = 'Parser::replaceInternalLinks' ;
1289
1290 wfProfileIn( $fname );
1291
1292 wfProfileIn( $fname.'-setup' );
1293 static $tc = FALSE;
1294 # the % is needed to support urlencoded titles as well
1295 if ( !$tc ) { $tc = Title::legalChars() . '#%'; }
1296
1297 $sk =& $this->mOptions->getSkin();
1298
1299 #split the entire text string on occurences of [[
1300 $a = explode( '[[', ' ' . $s );
1301 #get the first element (all text up to first [[), and remove the space we added
1302 $s = array_shift( $a );
1303 $s = substr( $s, 1 );
1304
1305 # Match a link having the form [[namespace:link|alternate]]trail
1306 static $e1 = FALSE;
1307 if ( !$e1 ) { $e1 = "/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD"; }
1308 # Match cases where there is no "]]", which might still be images
1309 static $e1_img = FALSE;
1310 if ( !$e1_img ) { $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD"; }
1311 # Match the end of a line for a word that's not followed by whitespace,
1312 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
1313 $e2 = wfMsgForContent( 'linkprefix' );
1314
1315 $useLinkPrefixExtension = $wgContLang->linkPrefixExtension();
1316
1317 if( is_null( $this->mTitle ) ) {
1318 wfDebugDieBacktrace( 'nooo' );
1319 }
1320 $nottalk = !$this->mTitle->isTalkPage();
1321
1322 if ( $useLinkPrefixExtension ) {
1323 if ( preg_match( $e2, $s, $m ) ) {
1324 $first_prefix = $m[2];
1325 } else {
1326 $first_prefix = false;
1327 }
1328 } else {
1329 $prefix = '';
1330 }
1331
1332 $selflink = $this->mTitle->getPrefixedText();
1333 wfProfileOut( $fname.'-setup' );
1334
1335 $checkVariantLink = sizeof($wgContLang->getVariants())>1;
1336 $useSubpages = $this->areSubpagesAllowed();
1337
1338 # Loop for each link
1339 for ($k = 0; isset( $a[$k] ); $k++) {
1340 $line = $a[$k];
1341 if ( $useLinkPrefixExtension ) {
1342 wfProfileIn( $fname.'-prefixhandling' );
1343 if ( preg_match( $e2, $s, $m ) ) {
1344 $prefix = $m[2];
1345 $s = $m[1];
1346 } else {
1347 $prefix='';
1348 }
1349 # first link
1350 if($first_prefix) {
1351 $prefix = $first_prefix;
1352 $first_prefix = false;
1353 }
1354 wfProfileOut( $fname.'-prefixhandling' );
1355 }
1356
1357 $might_be_img = false;
1358
1359 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
1360 $text = $m[2];
1361 # If we get a ] at the beginning of $m[3] that means we have a link that's something like:
1362 # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up,
1363 # the real problem is with the $e1 regex
1364 # See bug 1300.
1365 #
1366 # Still some problems for cases where the ] is meant to be outside punctuation,
1367 # and no image is in sight. See bug 2095.
1368 #
1369 if( $text !== '' && preg_match( "/^\](.*)/s", $m[3], $n ) ) {
1370 $text .= ']'; # so that replaceExternalLinks($text) works later
1371 $m[3] = $n[1];
1372 }
1373 # fix up urlencoded title texts
1374 if(preg_match('/%/', $m[1] )) $m[1] = urldecode($m[1]);
1375 $trail = $m[3];
1376 } elseif( preg_match($e1_img, $line, $m) ) { # Invalid, but might be an image with a link in its caption
1377 $might_be_img = true;
1378 $text = $m[2];
1379 if(preg_match('/%/', $m[1] )) $m[1] = urldecode($m[1]);
1380 $trail = "";
1381 } else { # Invalid form; output directly
1382 $s .= $prefix . '[[' . $line ;
1383 continue;
1384 }
1385
1386 # Don't allow internal links to pages containing
1387 # PROTO: where PROTO is a valid URL protocol; these
1388 # should be external links.
1389 if (preg_match('/^(\b(?:' . wfUrlProtocols() . '))/', $m[1])) {
1390 $s .= $prefix . '[[' . $line ;
1391 continue;
1392 }
1393
1394 # Make subpage if necessary
1395 if( $useSubpages ) {
1396 $link = $this->maybeDoSubpageLink( $m[1], $text );
1397 } else {
1398 $link = $m[1];
1399 }
1400
1401 $noforce = (substr($m[1], 0, 1) != ':');
1402 if (!$noforce) {
1403 # Strip off leading ':'
1404 $link = substr($link, 1);
1405 }
1406
1407 $nt = Title::newFromText( $this->unstripNoWiki($link, $this->mStripState) );
1408 if( !$nt ) {
1409 $s .= $prefix . '[[' . $line;
1410 continue;
1411 }
1412
1413 #check other language variants of the link
1414 #if the article does not exist
1415 if( $checkVariantLink
1416 && $nt->getArticleID() == 0 ) {
1417 $wgContLang->findVariantLink($link, $nt);
1418 }
1419
1420 $ns = $nt->getNamespace();
1421 $iw = $nt->getInterWiki();
1422
1423 if ($might_be_img) { # if this is actually an invalid link
1424 if ($ns == NS_IMAGE && $noforce) { #but might be an image
1425 $found = false;
1426 while (isset ($a[$k+1]) ) {
1427 #look at the next 'line' to see if we can close it there
1428 $spliced = array_splice( $a, $k + 1, 1 );
1429 $next_line = array_shift( $spliced );
1430 if( preg_match("/^(.*?]].*?)]](.*)$/sD", $next_line, $m) ) {
1431 # the first ]] closes the inner link, the second the image
1432 $found = true;
1433 $text .= '[[' . $m[1];
1434 $trail = $m[2];
1435 break;
1436 } elseif( preg_match("/^.*?]].*$/sD", $next_line, $m) ) {
1437 #if there's exactly one ]] that's fine, we'll keep looking
1438 $text .= '[[' . $m[0];
1439 } else {
1440 #if $next_line is invalid too, we need look no further
1441 $text .= '[[' . $next_line;
1442 break;
1443 }
1444 }
1445 if ( !$found ) {
1446 # we couldn't find the end of this imageLink, so output it raw
1447 #but don't ignore what might be perfectly normal links in the text we've examined
1448 $text = $this->replaceInternalLinks($text);
1449 $s .= $prefix . '[[' . $link . '|' . $text;
1450 # note: no $trail, because without an end, there *is* no trail
1451 continue;
1452 }
1453 } else { #it's not an image, so output it raw
1454 $s .= $prefix . '[[' . $link . '|' . $text;
1455 # note: no $trail, because without an end, there *is* no trail
1456 continue;
1457 }
1458 }
1459
1460 $wasblank = ( '' == $text );
1461 if( $wasblank ) $text = $link;
1462
1463
1464 # Link not escaped by : , create the various objects
1465 if( $noforce ) {
1466
1467 # Interwikis
1468 if( $iw && $this->mOptions->getInterwikiMagic() && $nottalk && $wgContLang->getLanguageName( $iw ) ) {
1469 $this->mOutput->addLanguageLink( $nt->getFullText() );
1470 $s = rtrim($s . "\n");
1471 $s .= trim($prefix . $trail, "\n") == '' ? '': $prefix . $trail;
1472 continue;
1473 }
1474
1475 if ( $ns == NS_IMAGE ) {
1476 wfProfileIn( "$fname-image" );
1477 if ( !wfIsBadImage( $nt->getDBkey() ) ) {
1478 # recursively parse links inside the image caption
1479 # actually, this will parse them in any other parameters, too,
1480 # but it might be hard to fix that, and it doesn't matter ATM
1481 $text = $this->replaceExternalLinks($text);
1482 $text = $this->replaceInternalLinks($text);
1483
1484 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
1485 $s .= $prefix . $this->armorLinks( $this->makeImage( $nt, $text ) ) . $trail;
1486 $this->mOutput->addImage( $nt->getDBkey() );
1487
1488 wfProfileOut( "$fname-image" );
1489 continue;
1490 }
1491 wfProfileOut( "$fname-image" );
1492
1493 }
1494
1495 if ( $ns == NS_CATEGORY ) {
1496 wfProfileIn( "$fname-category" );
1497 $s = rtrim($s . "\n"); # bug 87
1498
1499 if ( $wasblank ) {
1500 if ( $this->mTitle->getNamespace() == NS_CATEGORY ) {
1501 $sortkey = $this->mTitle->getText();
1502 } else {
1503 $sortkey = $this->mTitle->getPrefixedText();
1504 }
1505 } else {
1506 $sortkey = $text;
1507 }
1508 $sortkey = Sanitizer::decodeCharReferences( $sortkey );
1509 $sortkey = $wgContLang->convertCategoryKey( $sortkey );
1510 $this->mOutput->addCategory( $nt->getDBkey(), $sortkey );
1511
1512 /**
1513 * Strip the whitespace Category links produce, see bug 87
1514 * @todo We might want to use trim($tmp, "\n") here.
1515 */
1516 $s .= trim($prefix . $trail, "\n") == '' ? '': $prefix . $trail;
1517
1518 wfProfileOut( "$fname-category" );
1519 continue;
1520 }
1521 }
1522
1523 if( ( $nt->getPrefixedText() === $selflink ) &&
1524 ( $nt->getFragment() === '' ) ) {
1525 # Self-links are handled specially; generally de-link and change to bold.
1526 $s .= $prefix . $sk->makeSelfLinkObj( $nt, $text, '', $trail );
1527 continue;
1528 }
1529
1530 # Special and Media are pseudo-namespaces; no pages actually exist in them
1531 if( $ns == NS_MEDIA ) {
1532 $link = $sk->makeMediaLinkObj( $nt, $text );
1533 # Cloak with NOPARSE to avoid replacement in replaceExternalLinks
1534 $s .= $prefix . $this->armorLinks( $link ) . $trail;
1535 $this->mOutput->addImage( $nt->getDBkey() );
1536 continue;
1537 } elseif( $ns == NS_SPECIAL ) {
1538 $s .= $this->makeKnownLinkHolder( $nt, $text, '', $trail, $prefix );
1539 continue;
1540 } elseif( $ns == NS_IMAGE ) {
1541 $img = Image::newFromTitle( $nt );
1542 if( $img->exists() ) {
1543 // Force a blue link if the file exists; may be a remote
1544 // upload on the shared repository, and we want to see its
1545 // auto-generated page.
1546 $s .= $this->makeKnownLinkHolder( $nt, $text, '', $trail, $prefix );
1547 continue;
1548 }
1549 }
1550 $s .= $this->makeLinkHolder( $nt, $text, '', $trail, $prefix );
1551 }
1552 wfProfileOut( $fname );
1553 return $s;
1554 }
1555
1556 /**
1557 * Make a link placeholder. The text returned can be later resolved to a real link with
1558 * replaceLinkHolders(). This is done for two reasons: firstly to avoid further
1559 * parsing of interwiki links, and secondly to allow all extistence checks and
1560 * article length checks (for stub links) to be bundled into a single query.
1561 *
1562 */
1563 function makeLinkHolder( &$nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1564 if ( ! is_object($nt) ) {
1565 # Fail gracefully
1566 $retVal = "<!-- ERROR -->{$prefix}{$text}{$trail}";
1567 } else {
1568 # Separate the link trail from the rest of the link
1569 list( $inside, $trail ) = Linker::splitTrail( $trail );
1570
1571 if ( $nt->isExternal() ) {
1572 $nr = array_push( $this->mInterwikiLinkHolders['texts'], $prefix.$text.$inside );
1573 $this->mInterwikiLinkHolders['titles'][] = $nt;
1574 $retVal = '<!--IWLINK '. ($nr-1) ."-->{$trail}";
1575 } else {
1576 $nr = array_push( $this->mLinkHolders['namespaces'], $nt->getNamespace() );
1577 $this->mLinkHolders['dbkeys'][] = $nt->getDBkey();
1578 $this->mLinkHolders['queries'][] = $query;
1579 $this->mLinkHolders['texts'][] = $prefix.$text.$inside;
1580 $this->mLinkHolders['titles'][] = $nt;
1581
1582 $retVal = '<!--LINK '. ($nr-1) ."-->{$trail}";
1583 }
1584 }
1585 return $retVal;
1586 }
1587
1588 /**
1589 * Render a forced-blue link inline; protect against double expansion of
1590 * URLs if we're in a mode that prepends full URL prefixes to internal links.
1591 * Since this little disaster has to split off the trail text to avoid
1592 * breaking URLs in the following text without breaking trails on the
1593 * wiki links, it's been made into a horrible function.
1594 *
1595 * @param Title $nt
1596 * @param string $text
1597 * @param string $query
1598 * @param string $trail
1599 * @param string $prefix
1600 * @return string HTML-wikitext mix oh yuck
1601 */
1602 function makeKnownLinkHolder( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1603 list( $inside, $trail ) = Linker::splitTrail( $trail );
1604 $sk =& $this->mOptions->getSkin();
1605 $link = $sk->makeKnownLinkObj( $nt, $text, $query, $inside, $prefix );
1606 return $this->armorLinks( $link ) . $trail;
1607 }
1608
1609 /**
1610 * Insert a NOPARSE hacky thing into any inline links in a chunk that's
1611 * going to go through further parsing steps before inline URL expansion.
1612 *
1613 * In particular this is important when using action=render, which causes
1614 * full URLs to be included.
1615 *
1616 * Oh man I hate our multi-layer parser!
1617 *
1618 * @param string more-or-less HTML
1619 * @return string less-or-more HTML with NOPARSE bits
1620 */
1621 function armorLinks( $text ) {
1622 return preg_replace( "/\b(" . wfUrlProtocols() . ')/',
1623 "{$this->mUniqPrefix}NOPARSE$1", $text );
1624 }
1625
1626 /**
1627 * Return true if subpage links should be expanded on this page.
1628 * @return bool
1629 */
1630 function areSubpagesAllowed() {
1631 # Some namespaces don't allow subpages
1632 global $wgNamespacesWithSubpages;
1633 return !empty($wgNamespacesWithSubpages[$this->mTitle->getNamespace()]);
1634 }
1635
1636 /**
1637 * Handle link to subpage if necessary
1638 * @param string $target the source of the link
1639 * @param string &$text the link text, modified as necessary
1640 * @return string the full name of the link
1641 * @access private
1642 */
1643 function maybeDoSubpageLink($target, &$text) {
1644 # Valid link forms:
1645 # Foobar -- normal
1646 # :Foobar -- override special treatment of prefix (images, language links)
1647 # /Foobar -- convert to CurrentPage/Foobar
1648 # /Foobar/ -- convert to CurrentPage/Foobar, strip the initial / from text
1649 # ../ -- convert to CurrentPage, from CurrentPage/CurrentSubPage
1650 # ../Foobar -- convert to CurrentPage/Foobar, from CurrentPage/CurrentSubPage
1651
1652 $fname = 'Parser::maybeDoSubpageLink';
1653 wfProfileIn( $fname );
1654 $ret = $target; # default return value is no change
1655
1656 # Some namespaces don't allow subpages,
1657 # so only perform processing if subpages are allowed
1658 if( $this->areSubpagesAllowed() ) {
1659 # Look at the first character
1660 if( $target != '' && $target{0} == '/' ) {
1661 # / at end means we don't want the slash to be shown
1662 if( substr( $target, -1, 1 ) == '/' ) {
1663 $target = substr( $target, 1, -1 );
1664 $noslash = $target;
1665 } else {
1666 $noslash = substr( $target, 1 );
1667 }
1668
1669 $ret = $this->mTitle->getPrefixedText(). '/' . trim($noslash);
1670 if( '' === $text ) {
1671 $text = $target;
1672 } # this might be changed for ugliness reasons
1673 } else {
1674 # check for .. subpage backlinks
1675 $dotdotcount = 0;
1676 $nodotdot = $target;
1677 while( strncmp( $nodotdot, "../", 3 ) == 0 ) {
1678 ++$dotdotcount;
1679 $nodotdot = substr( $nodotdot, 3 );
1680 }
1681 if($dotdotcount > 0) {
1682 $exploded = explode( '/', $this->mTitle->GetPrefixedText() );
1683 if( count( $exploded ) > $dotdotcount ) { # not allowed to go below top level page
1684 $ret = implode( '/', array_slice( $exploded, 0, -$dotdotcount ) );
1685 # / at the end means don't show full path
1686 if( substr( $nodotdot, -1, 1 ) == '/' ) {
1687 $nodotdot = substr( $nodotdot, 0, -1 );
1688 if( '' === $text ) {
1689 $text = $nodotdot;
1690 }
1691 }
1692 $nodotdot = trim( $nodotdot );
1693 if( $nodotdot != '' ) {
1694 $ret .= '/' . $nodotdot;
1695 }
1696 }
1697 }
1698 }
1699 }
1700
1701 wfProfileOut( $fname );
1702 return $ret;
1703 }
1704
1705 /**#@+
1706 * Used by doBlockLevels()
1707 * @access private
1708 */
1709 /* private */ function closeParagraph() {
1710 $result = '';
1711 if ( '' != $this->mLastSection ) {
1712 $result = '</' . $this->mLastSection . ">\n";
1713 }
1714 $this->mInPre = false;
1715 $this->mLastSection = '';
1716 return $result;
1717 }
1718 # getCommon() returns the length of the longest common substring
1719 # of both arguments, starting at the beginning of both.
1720 #
1721 /* private */ function getCommon( $st1, $st2 ) {
1722 $fl = strlen( $st1 );
1723 $shorter = strlen( $st2 );
1724 if ( $fl < $shorter ) { $shorter = $fl; }
1725
1726 for ( $i = 0; $i < $shorter; ++$i ) {
1727 if ( $st1{$i} != $st2{$i} ) { break; }
1728 }
1729 return $i;
1730 }
1731 # These next three functions open, continue, and close the list
1732 # element appropriate to the prefix character passed into them.
1733 #
1734 /* private */ function openList( $char ) {
1735 $result = $this->closeParagraph();
1736
1737 if ( '*' == $char ) { $result .= '<ul><li>'; }
1738 else if ( '#' == $char ) { $result .= '<ol><li>'; }
1739 else if ( ':' == $char ) { $result .= '<dl><dd>'; }
1740 else if ( ';' == $char ) {
1741 $result .= '<dl><dt>';
1742 $this->mDTopen = true;
1743 }
1744 else { $result = '<!-- ERR 1 -->'; }
1745
1746 return $result;
1747 }
1748
1749 /* private */ function nextItem( $char ) {
1750 if ( '*' == $char || '#' == $char ) { return '</li><li>'; }
1751 else if ( ':' == $char || ';' == $char ) {
1752 $close = '</dd>';
1753 if ( $this->mDTopen ) { $close = '</dt>'; }
1754 if ( ';' == $char ) {
1755 $this->mDTopen = true;
1756 return $close . '<dt>';
1757 } else {
1758 $this->mDTopen = false;
1759 return $close . '<dd>';
1760 }
1761 }
1762 return '<!-- ERR 2 -->';
1763 }
1764
1765 /* private */ function closeList( $char ) {
1766 if ( '*' == $char ) { $text = '</li></ul>'; }
1767 else if ( '#' == $char ) { $text = '</li></ol>'; }
1768 else if ( ':' == $char ) {
1769 if ( $this->mDTopen ) {
1770 $this->mDTopen = false;
1771 $text = '</dt></dl>';
1772 } else {
1773 $text = '</dd></dl>';
1774 }
1775 }
1776 else { return '<!-- ERR 3 -->'; }
1777 return $text."\n";
1778 }
1779 /**#@-*/
1780
1781 /**
1782 * Make lists from lines starting with ':', '*', '#', etc.
1783 *
1784 * @access private
1785 * @return string the lists rendered as HTML
1786 */
1787 function doBlockLevels( $text, $linestart ) {
1788 $fname = 'Parser::doBlockLevels';
1789 wfProfileIn( $fname );
1790
1791 # Parsing through the text line by line. The main thing
1792 # happening here is handling of block-level elements p, pre,
1793 # and making lists from lines starting with * # : etc.
1794 #
1795 $textLines = explode( "\n", $text );
1796
1797 $lastPrefix = $output = '';
1798 $this->mDTopen = $inBlockElem = false;
1799 $prefixLength = 0;
1800 $paragraphStack = false;
1801
1802 if ( !$linestart ) {
1803 $output .= array_shift( $textLines );
1804 }
1805 foreach ( $textLines as $oLine ) {
1806 $lastPrefixLength = strlen( $lastPrefix );
1807 $preCloseMatch = preg_match('/<\\/pre/i', $oLine );
1808 $preOpenMatch = preg_match('/<pre/i', $oLine );
1809 if ( !$this->mInPre ) {
1810 # Multiple prefixes may abut each other for nested lists.
1811 $prefixLength = strspn( $oLine, '*#:;' );
1812 $pref = substr( $oLine, 0, $prefixLength );
1813
1814 # eh?
1815 $pref2 = str_replace( ';', ':', $pref );
1816 $t = substr( $oLine, $prefixLength );
1817 $this->mInPre = !empty($preOpenMatch);
1818 } else {
1819 # Don't interpret any other prefixes in preformatted text
1820 $prefixLength = 0;
1821 $pref = $pref2 = '';
1822 $t = $oLine;
1823 }
1824
1825 # List generation
1826 if( $prefixLength && 0 == strcmp( $lastPrefix, $pref2 ) ) {
1827 # Same as the last item, so no need to deal with nesting or opening stuff
1828 $output .= $this->nextItem( substr( $pref, -1 ) );
1829 $paragraphStack = false;
1830
1831 if ( substr( $pref, -1 ) == ';') {
1832 # The one nasty exception: definition lists work like this:
1833 # ; title : definition text
1834 # So we check for : in the remainder text to split up the
1835 # title and definition, without b0rking links.
1836 $term = $t2 = '';
1837 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
1838 $t = $t2;
1839 $output .= $term . $this->nextItem( ':' );
1840 }
1841 }
1842 } elseif( $prefixLength || $lastPrefixLength ) {
1843 # Either open or close a level...
1844 $commonPrefixLength = $this->getCommon( $pref, $lastPrefix );
1845 $paragraphStack = false;
1846
1847 while( $commonPrefixLength < $lastPrefixLength ) {
1848 $output .= $this->closeList( $lastPrefix{$lastPrefixLength-1} );
1849 --$lastPrefixLength;
1850 }
1851 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
1852 $output .= $this->nextItem( $pref{$commonPrefixLength-1} );
1853 }
1854 while ( $prefixLength > $commonPrefixLength ) {
1855 $char = substr( $pref, $commonPrefixLength, 1 );
1856 $output .= $this->openList( $char );
1857
1858 if ( ';' == $char ) {
1859 # FIXME: This is dupe of code above
1860 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
1861 $t = $t2;
1862 $output .= $term . $this->nextItem( ':' );
1863 }
1864 }
1865 ++$commonPrefixLength;
1866 }
1867 $lastPrefix = $pref2;
1868 }
1869 if( 0 == $prefixLength ) {
1870 wfProfileIn( "$fname-paragraph" );
1871 # No prefix (not in list)--go to paragraph mode
1872 // XXX: use a stack for nestable elements like span, table and div
1873 $openmatch = preg_match('/(<table|<blockquote|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|<p|<ul|<li|<\\/tr|<\\/td|<\\/th)/iS', $t );
1874 $closematch = preg_match(
1875 '/(<\\/table|<\\/blockquote|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|'.
1876 '<td|<th|<div|<\\/div|<hr|<\\/pre|<\\/p|'.$this->mUniqPrefix.'-pre|<\\/li|<\\/ul)/iS', $t );
1877 if ( $openmatch or $closematch ) {
1878 $paragraphStack = false;
1879 $output .= $this->closeParagraph();
1880 if ( $preOpenMatch and !$preCloseMatch ) {
1881 $this->mInPre = true;
1882 }
1883 if ( $closematch ) {
1884 $inBlockElem = false;
1885 } else {
1886 $inBlockElem = true;
1887 }
1888 } else if ( !$inBlockElem && !$this->mInPre ) {
1889 if ( ' ' == $t{0} and ( $this->mLastSection == 'pre' or trim($t) != '' ) ) {
1890 // pre
1891 if ($this->mLastSection != 'pre') {
1892 $paragraphStack = false;
1893 $output .= $this->closeParagraph().'<pre>';
1894 $this->mLastSection = 'pre';
1895 }
1896 $t = substr( $t, 1 );
1897 } else {
1898 // paragraph
1899 if ( '' == trim($t) ) {
1900 if ( $paragraphStack ) {
1901 $output .= $paragraphStack.'<br />';
1902 $paragraphStack = false;
1903 $this->mLastSection = 'p';
1904 } else {
1905 if ($this->mLastSection != 'p' ) {
1906 $output .= $this->closeParagraph();
1907 $this->mLastSection = '';
1908 $paragraphStack = '<p>';
1909 } else {
1910 $paragraphStack = '</p><p>';
1911 }
1912 }
1913 } else {
1914 if ( $paragraphStack ) {
1915 $output .= $paragraphStack;
1916 $paragraphStack = false;
1917 $this->mLastSection = 'p';
1918 } else if ($this->mLastSection != 'p') {
1919 $output .= $this->closeParagraph().'<p>';
1920 $this->mLastSection = 'p';
1921 }
1922 }
1923 }
1924 }
1925 wfProfileOut( "$fname-paragraph" );
1926 }
1927 // somewhere above we forget to get out of pre block (bug 785)
1928 if($preCloseMatch && $this->mInPre) {
1929 $this->mInPre = false;
1930 }
1931 if ($paragraphStack === false) {
1932 $output .= $t."\n";
1933 }
1934 }
1935 while ( $prefixLength ) {
1936 $output .= $this->closeList( $pref2{$prefixLength-1} );
1937 --$prefixLength;
1938 }
1939 if ( '' != $this->mLastSection ) {
1940 $output .= '</' . $this->mLastSection . '>';
1941 $this->mLastSection = '';
1942 }
1943
1944 wfProfileOut( $fname );
1945 return $output;
1946 }
1947
1948 /**
1949 * Split up a string on ':', ignoring any occurences inside
1950 * <a>..</a> or <span>...</span>
1951 * @param string $str the string to split
1952 * @param string &$before set to everything before the ':'
1953 * @param string &$after set to everything after the ':'
1954 * return string the position of the ':', or false if none found
1955 */
1956 function findColonNoLinks($str, &$before, &$after) {
1957 # I wonder if we should make this count all tags, not just <a>
1958 # and <span>. That would prevent us from matching a ':' that
1959 # comes in the middle of italics other such formatting....
1960 # -- Wil
1961 $fname = 'Parser::findColonNoLinks';
1962 wfProfileIn( $fname );
1963 $pos = 0;
1964 do {
1965 $colon = strpos($str, ':', $pos);
1966
1967 if ($colon !== false) {
1968 $before = substr($str, 0, $colon);
1969 $after = substr($str, $colon + 1);
1970
1971 # Skip any ':' within <a> or <span> pairs
1972 $a = substr_count($before, '<a');
1973 $s = substr_count($before, '<span');
1974 $ca = substr_count($before, '</a>');
1975 $cs = substr_count($before, '</span>');
1976
1977 if ($a <= $ca and $s <= $cs) {
1978 # Tags are balanced before ':'; ok
1979 break;
1980 }
1981 $pos = $colon + 1;
1982 }
1983 } while ($colon !== false);
1984 wfProfileOut( $fname );
1985 return $colon;
1986 }
1987
1988 /**
1989 * Return value of a magic variable (like PAGENAME)
1990 *
1991 * @access private
1992 */
1993 function getVariableValue( $index ) {
1994 global $wgContLang, $wgSitename, $wgServer, $wgServerName, $wgScriptPath;
1995
1996 /**
1997 * Some of these require message or data lookups and can be
1998 * expensive to check many times.
1999 */
2000 static $varCache = array();
2001 if ( wfRunHooks( 'ParserGetVariableValueVarCache', array( &$this, &$varCache ) ) )
2002 if ( isset( $varCache[$index] ) )
2003 return $varCache[$index];
2004
2005 $ts = time();
2006 wfRunHooks( 'ParserGetVariableValueTs', array( &$this, &$ts ) );
2007
2008 switch ( $index ) {
2009 case MAG_CURRENTMONTH:
2010 return $varCache[$index] = $wgContLang->formatNum( date( 'm', $ts ) );
2011 case MAG_CURRENTMONTHNAME:
2012 return $varCache[$index] = $wgContLang->getMonthName( date( 'n', $ts ) );
2013 case MAG_CURRENTMONTHNAMEGEN:
2014 return $varCache[$index] = $wgContLang->getMonthNameGen( date( 'n', $ts ) );
2015 case MAG_CURRENTMONTHABBREV:
2016 return $varCache[$index] = $wgContLang->getMonthAbbreviation( date( 'n', $ts ) );
2017 case MAG_CURRENTDAY:
2018 return $varCache[$index] = $wgContLang->formatNum( date( 'j', $ts ) );
2019 case MAG_CURRENTDAY2:
2020 return $varCache[$index] = $wgContLang->formatNum( date( 'd', $ts ) );
2021 case MAG_PAGENAME:
2022 return $this->mTitle->getText();
2023 case MAG_PAGENAMEE:
2024 return $this->mTitle->getPartialURL();
2025 case MAG_FULLPAGENAME:
2026 return $this->mTitle->getPrefixedText();
2027 case MAG_FULLPAGENAMEE:
2028 return $this->mTitle->getPrefixedURL();
2029 case MAG_REVISIONID:
2030 return $this->mRevisionId;
2031 case MAG_NAMESPACE:
2032 return $wgContLang->getNsText( $this->mTitle->getNamespace() );
2033 case MAG_NAMESPACEE:
2034 return wfUrlencode( $wgContLang->getNsText( $this->mTitle->getNamespace() ) );
2035 case MAG_CURRENTDAYNAME:
2036 return $varCache[$index] = $wgContLang->getWeekdayName( date( 'w', $ts ) + 1 );
2037 case MAG_CURRENTYEAR:
2038 return $varCache[$index] = $wgContLang->formatNum( date( 'Y', $ts ), true );
2039 case MAG_CURRENTTIME:
2040 return $varCache[$index] = $wgContLang->time( wfTimestamp( TS_MW, $ts ), false, false );
2041 case MAG_CURRENTWEEK:
2042 // @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2043 // int to remove the padding
2044 return $varCache[$index] = $wgContLang->formatNum( (int)date( 'W', $ts ) );
2045 case MAG_CURRENTDOW:
2046 return $varCache[$index] = $wgContLang->formatNum( date( 'w', $ts ) );
2047 case MAG_NUMBEROFARTICLES:
2048 return $varCache[$index] = $wgContLang->formatNum( wfNumberOfArticles() );
2049 case MAG_NUMBEROFFILES:
2050 return $varCache[$index] = $wgContLang->formatNum( wfNumberOfFiles() );
2051 case MAG_SITENAME:
2052 return $wgSitename;
2053 case MAG_SERVER:
2054 return $wgServer;
2055 case MAG_SERVERNAME:
2056 return $wgServerName;
2057 case MAG_SCRIPTPATH:
2058 return $wgScriptPath;
2059 default:
2060 $ret = null;
2061 if ( wfRunHooks( 'ParserGetVariableValueSwitch', array( &$this, &$varCache, &$index, &$ret ) ) )
2062 return $ret;
2063 else
2064 return null;
2065 }
2066 }
2067
2068 /**
2069 * initialise the magic variables (like CURRENTMONTHNAME)
2070 *
2071 * @access private
2072 */
2073 function initialiseVariables() {
2074 $fname = 'Parser::initialiseVariables';
2075 wfProfileIn( $fname );
2076 global $wgVariableIDs;
2077 $this->mVariables = array();
2078 foreach ( $wgVariableIDs as $id ) {
2079 $mw =& MagicWord::get( $id );
2080 $mw->addToArray( $this->mVariables, $id );
2081 }
2082 wfProfileOut( $fname );
2083 }
2084
2085 /**
2086 * parse any parentheses in format ((title|part|part))
2087 * and call callbacks to get a replacement text for any found piece
2088 *
2089 * @param string $text The text to parse
2090 * @param array $callbacks rules in form:
2091 * '{' => array( # opening parentheses
2092 * 'end' => '}', # closing parentheses
2093 * 'cb' => array(2 => callback, # replacement callback to call if {{..}} is found
2094 * 4 => callback # replacement callback to call if {{{{..}}}} is found
2095 * )
2096 * )
2097 * @access private
2098 */
2099 function replace_callback ($text, $callbacks) {
2100 $openingBraceStack = array(); # this array will hold a stack of parentheses which are not closed yet
2101 $lastOpeningBrace = -1; # last not closed parentheses
2102
2103 for ($i = 0; $i < strlen($text); $i++) {
2104 # check for any opening brace
2105 $rule = null;
2106 $nextPos = -1;
2107 foreach ($callbacks as $key => $value) {
2108 $pos = strpos ($text, $key, $i);
2109 if (false !== $pos && (-1 == $nextPos || $pos < $nextPos)) {
2110 $rule = $value;
2111 $nextPos = $pos;
2112 }
2113 }
2114
2115 if ($lastOpeningBrace >= 0) {
2116 $pos = strpos ($text, $openingBraceStack[$lastOpeningBrace]['braceEnd'], $i);
2117
2118 if (false !== $pos && (-1 == $nextPos || $pos < $nextPos)){
2119 $rule = null;
2120 $nextPos = $pos;
2121 }
2122
2123 $pos = strpos ($text, '|', $i);
2124
2125 if (false !== $pos && (-1 == $nextPos || $pos < $nextPos)){
2126 $rule = null;
2127 $nextPos = $pos;
2128 }
2129 }
2130
2131 if ($nextPos == -1)
2132 break;
2133
2134 $i = $nextPos;
2135
2136 # found openning brace, lets add it to parentheses stack
2137 if (null != $rule) {
2138 $piece = array('brace' => $text[$i],
2139 'braceEnd' => $rule['end'],
2140 'count' => 1,
2141 'title' => '',
2142 'parts' => null);
2143
2144 # count openning brace characters
2145 while ($i+1 < strlen($text) && $text[$i+1] == $piece['brace']) {
2146 $piece['count']++;
2147 $i++;
2148 }
2149
2150 $piece['startAt'] = $i+1;
2151 $piece['partStart'] = $i+1;
2152
2153 # we need to add to stack only if openning brace count is enough for any given rule
2154 foreach ($rule['cb'] as $cnt => $fn) {
2155 if ($piece['count'] >= $cnt) {
2156 $lastOpeningBrace ++;
2157 $openingBraceStack[$lastOpeningBrace] = $piece;
2158 break;
2159 }
2160 }
2161
2162 continue;
2163 }
2164 else if ($lastOpeningBrace >= 0) {
2165 # first check if it is a closing brace
2166 if ($openingBraceStack[$lastOpeningBrace]['braceEnd'] == $text[$i]) {
2167 # lets check if it is enough characters for closing brace
2168 $count = 1;
2169 while ($i+$count < strlen($text) && $text[$i+$count] == $text[$i])
2170 $count++;
2171
2172 # if there are more closing parentheses than opening ones, we parse less
2173 if ($openingBraceStack[$lastOpeningBrace]['count'] < $count)
2174 $count = $openingBraceStack[$lastOpeningBrace]['count'];
2175
2176 # check for maximum matching characters (if there are 5 closing characters, we will probably need only 3 - depending on the rules)
2177 $matchingCount = 0;
2178 $matchingCallback = null;
2179 foreach ($callbacks[$openingBraceStack[$lastOpeningBrace]['brace']]['cb'] as $cnt => $fn) {
2180 if ($count >= $cnt && $matchingCount < $cnt) {
2181 $matchingCount = $cnt;
2182 $matchingCallback = $fn;
2183 }
2184 }
2185
2186 if ($matchingCount == 0) {
2187 $i += $count - 1;
2188 continue;
2189 }
2190
2191 # lets set a title or last part (if '|' was found)
2192 if (null === $openingBraceStack[$lastOpeningBrace]['parts'])
2193 $openingBraceStack[$lastOpeningBrace]['title'] = substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'], $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2194 else
2195 $openingBraceStack[$lastOpeningBrace]['parts'][] = substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'], $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2196
2197 $pieceStart = $openingBraceStack[$lastOpeningBrace]['startAt'] - $matchingCount;
2198 $pieceEnd = $i + $matchingCount;
2199
2200 if( is_callable( $matchingCallback ) ) {
2201 $cbArgs = array (
2202 'text' => substr($text, $pieceStart, $pieceEnd - $pieceStart),
2203 'title' => trim($openingBraceStack[$lastOpeningBrace]['title']),
2204 'parts' => $openingBraceStack[$lastOpeningBrace]['parts'],
2205 'lineStart' => (($pieceStart > 0) && ($text[$pieceStart-1] == '\n')),
2206 );
2207 # finally we can call a user callback and replace piece of text
2208 $replaceWith = call_user_func( $matchingCallback, $cbArgs );
2209 $text = substr($text, 0, $pieceStart) . $replaceWith . substr($text, $pieceEnd);
2210 $i = $pieceStart + strlen($replaceWith) - 1;
2211 }
2212 else {
2213 # null value for callback means that parentheses should be parsed, but not replaced
2214 $i += $matchingCount - 1;
2215 }
2216
2217 # reset last openning parentheses, but keep it in case there are unused characters
2218 $piece = array('brace' => $openingBraceStack[$lastOpeningBrace]['brace'],
2219 'braceEnd' => $openingBraceStack[$lastOpeningBrace]['braceEnd'],
2220 'count' => $openingBraceStack[$lastOpeningBrace]['count'],
2221 'title' => '',
2222 'parts' => null,
2223 'startAt' => $openingBraceStack[$lastOpeningBrace]['startAt']);
2224 $openingBraceStack[$lastOpeningBrace--] = null;
2225
2226 if ($matchingCount < $piece['count']) {
2227 $piece['count'] -= $matchingCount;
2228 $piece['startAt'] -= $matchingCount;
2229 $piece['partStart'] = $piece['startAt'];
2230 # do we still qualify for any callback with remaining count?
2231 foreach ($callbacks[$piece['brace']]['cb'] as $cnt => $fn) {
2232 if ($piece['count'] >= $cnt) {
2233 $lastOpeningBrace ++;
2234 $openingBraceStack[$lastOpeningBrace] = $piece;
2235 break;
2236 }
2237 }
2238 }
2239 continue;
2240 }
2241
2242 # lets set a title if it is a first separator, or next part otherwise
2243 if ($text[$i] == '|') {
2244 if (null === $openingBraceStack[$lastOpeningBrace]['parts']) {
2245 $openingBraceStack[$lastOpeningBrace]['title'] = substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'], $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2246 $openingBraceStack[$lastOpeningBrace]['parts'] = array();
2247 }
2248 else
2249 $openingBraceStack[$lastOpeningBrace]['parts'][] = substr($text, $openingBraceStack[$lastOpeningBrace]['partStart'], $i - $openingBraceStack[$lastOpeningBrace]['partStart']);
2250
2251 $openingBraceStack[$lastOpeningBrace]['partStart'] = $i + 1;
2252 }
2253 }
2254 }
2255
2256 return $text;
2257 }
2258
2259 /**
2260 * Replace magic variables, templates, and template arguments
2261 * with the appropriate text. Templates are substituted recursively,
2262 * taking care to avoid infinite loops.
2263 *
2264 * Note that the substitution depends on value of $mOutputType:
2265 * OT_WIKI: only {{subst:}} templates
2266 * OT_MSG: only magic variables
2267 * OT_HTML: all templates and magic variables
2268 *
2269 * @param string $tex The text to transform
2270 * @param array $args Key-value pairs representing template parameters to substitute
2271 * @param bool $argsOnly Only do argument (triple-brace) expansion, not double-brace expansion
2272 * @access private
2273 */
2274 function replaceVariables( $text, $args = array(), $argsOnly = false ) {
2275 # Prevent too big inclusions
2276 if( strlen( $text ) > MAX_INCLUDE_SIZE ) {
2277 return $text;
2278 }
2279
2280 $fname = 'Parser::replaceVariables';
2281 wfProfileIn( $fname );
2282
2283 # This function is called recursively. To keep track of arguments we need a stack:
2284 array_push( $this->mArgStack, $args );
2285
2286 $braceCallbacks = array();
2287 if ( !$argsOnly ) {
2288 $braceCallbacks[2] = array( &$this, 'braceSubstitution' );
2289 }
2290 if ( $this->mOutputType == OT_HTML || $this->mOutputType == OT_WIKI ) {
2291 $braceCallbacks[3] = array( &$this, 'argSubstitution' );
2292 }
2293 $callbacks = array();
2294 $callbacks['{'] = array('end' => '}', 'cb' => $braceCallbacks);
2295 $callbacks['['] = array('end' => ']', 'cb' => array(2=>null));
2296 $text = $this->replace_callback ($text, $callbacks);
2297
2298 array_pop( $this->mArgStack );
2299
2300 wfProfileOut( $fname );
2301 return $text;
2302 }
2303
2304 /**
2305 * Replace magic variables
2306 * @access private
2307 */
2308 function variableSubstitution( $matches ) {
2309 $fname = 'Parser::variableSubstitution';
2310 $varname = $matches[1];
2311 wfProfileIn( $fname );
2312 if ( !$this->mVariables ) {
2313 $this->initialiseVariables();
2314 }
2315 $skip = false;
2316 if ( $this->mOutputType == OT_WIKI ) {
2317 # Do only magic variables prefixed by SUBST
2318 $mwSubst =& MagicWord::get( MAG_SUBST );
2319 if (!$mwSubst->matchStartAndRemove( $varname ))
2320 $skip = true;
2321 # Note that if we don't substitute the variable below,
2322 # we don't remove the {{subst:}} magic word, in case
2323 # it is a template rather than a magic variable.
2324 }
2325 if ( !$skip && array_key_exists( $varname, $this->mVariables ) ) {
2326 $id = $this->mVariables[$varname];
2327 $text = $this->getVariableValue( $id );
2328 $this->mOutput->mContainsOldMagic = true;
2329 } else {
2330 $text = $matches[0];
2331 }
2332 wfProfileOut( $fname );
2333 return $text;
2334 }
2335
2336 # Split template arguments
2337 function getTemplateArgs( $argsString ) {
2338 if ( $argsString === '' ) {
2339 return array();
2340 }
2341
2342 $args = explode( '|', substr( $argsString, 1 ) );
2343
2344 # If any of the arguments contains a '[[' but no ']]', it needs to be
2345 # merged with the next arg because the '|' character between belongs
2346 # to the link syntax and not the template parameter syntax.
2347 $argc = count($args);
2348
2349 for ( $i = 0; $i < $argc-1; $i++ ) {
2350 if ( substr_count ( $args[$i], '[[' ) != substr_count ( $args[$i], ']]' ) ) {
2351 $args[$i] .= '|'.$args[$i+1];
2352 array_splice($args, $i+1, 1);
2353 $i--;
2354 $argc--;
2355 }
2356 }
2357
2358 return $args;
2359 }
2360
2361 /**
2362 * Return the text of a template, after recursively
2363 * replacing any variables or templates within the template.
2364 *
2365 * @param array $piece The parts of the template
2366 * $piece['text']: matched text
2367 * $piece['title']: the title, i.e. the part before the |
2368 * $piece['parts']: the parameter array
2369 * @return string the text of the template
2370 * @access private
2371 */
2372 function braceSubstitution( $piece ) {
2373 global $wgContLang;
2374 $fname = 'Parser::braceSubstitution';
2375 wfProfileIn( $fname );
2376
2377 # Flags
2378 $found = false; # $text has been filled
2379 $nowiki = false; # wiki markup in $text should be escaped
2380 $noparse = false; # Unsafe HTML tags should not be stripped, etc.
2381 $noargs = false; # Don't replace triple-brace arguments in $text
2382 $replaceHeadings = false; # Make the edit section links go to the template not the article
2383 $isHTML = false; # $text is HTML, armour it against wikitext transformation
2384 $forceRawInterwiki = false; # Force interwiki transclusion to be done in raw mode not rendered
2385
2386 # Title object, where $text came from
2387 $title = NULL;
2388
2389 $linestart = '';
2390
2391 # $part1 is the bit before the first |, and must contain only title characters
2392 # $args is a list of arguments, starting from index 0, not including $part1
2393
2394 $part1 = $piece['title'];
2395 # If the third subpattern matched anything, it will start with |
2396
2397 if (null == $piece['parts']) {
2398 $replaceWith = $this->variableSubstitution (array ($piece['text'], $piece['title']));
2399 if ($replaceWith != $piece['text']) {
2400 $text = $replaceWith;
2401 $found = true;
2402 $noparse = true;
2403 $noargs = true;
2404 }
2405 }
2406
2407 $args = (null == $piece['parts']) ? array() : $piece['parts'];
2408 $argc = count( $args );
2409
2410 # SUBST
2411 if ( !$found ) {
2412 $mwSubst =& MagicWord::get( MAG_SUBST );
2413 if ( $mwSubst->matchStartAndRemove( $part1 ) xor ($this->mOutputType == OT_WIKI) ) {
2414 # One of two possibilities is true:
2415 # 1) Found SUBST but not in the PST phase
2416 # 2) Didn't find SUBST and in the PST phase
2417 # In either case, return without further processing
2418 $text = $piece['text'];
2419 $found = true;
2420 $noparse = true;
2421 $noargs = true;
2422 }
2423 }
2424
2425 # MSG, MSGNW, INT and RAW
2426 if ( !$found ) {
2427 # Check for MSGNW:
2428 $mwMsgnw =& MagicWord::get( MAG_MSGNW );
2429 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
2430 $nowiki = true;
2431 } else {
2432 # Remove obsolete MSG:
2433 $mwMsg =& MagicWord::get( MAG_MSG );
2434 $mwMsg->matchStartAndRemove( $part1 );
2435 }
2436
2437 # Check for RAW:
2438 $mwRaw =& MagicWord::get( MAG_RAW );
2439 if ( $mwRaw->matchStartAndRemove( $part1 ) ) {
2440 $forceRawInterwiki = true;
2441 }
2442
2443 # Check if it is an internal message
2444 $mwInt =& MagicWord::get( MAG_INT );
2445 if ( $mwInt->matchStartAndRemove( $part1 ) ) {
2446 if ( $this->incrementIncludeCount( 'int:'.$part1 ) ) {
2447 $text = $linestart . wfMsgReal( $part1, $args, true );
2448 $found = true;
2449 }
2450 }
2451 }
2452
2453 # NS
2454 if ( !$found ) {
2455 # Check for NS: (namespace expansion)
2456 $mwNs = MagicWord::get( MAG_NS );
2457 if ( $mwNs->matchStartAndRemove( $part1 ) ) {
2458 if ( intval( $part1 ) || $part1 == "0" ) {
2459 $text = $linestart . $wgContLang->getNsText( intval( $part1 ) );
2460 $found = true;
2461 } else {
2462 $index = Namespace::getCanonicalIndex( strtolower( $part1 ) );
2463 if ( !is_null( $index ) ) {
2464 $text = $linestart . $wgContLang->getNsText( $index );
2465 $found = true;
2466 }
2467 }
2468 }
2469 }
2470
2471 # LCFIRST, UCFIRST, LC and UC
2472 if ( !$found ) {
2473 $lcfirst =& MagicWord::get( MAG_LCFIRST );
2474 $ucfirst =& MagicWord::get( MAG_UCFIRST );
2475 $lc =& MagicWord::get( MAG_LC );
2476 $uc =& MagicWord::get( MAG_UC );
2477 if ( $lcfirst->matchStartAndRemove( $part1 ) ) {
2478 $text = $linestart . $wgContLang->lcfirst( $part1 );
2479 $found = true;
2480 } else if ( $ucfirst->matchStartAndRemove( $part1 ) ) {
2481 $text = $linestart . $wgContLang->ucfirst( $part1 );
2482 $found = true;
2483 } else if ( $lc->matchStartAndRemove( $part1 ) ) {
2484 $text = $linestart . $wgContLang->lc( $part1 );
2485 $found = true;
2486 } else if ( $uc->matchStartAndRemove( $part1 ) ) {
2487 $text = $linestart . $wgContLang->uc( $part1 );
2488 $found = true;
2489 }
2490 }
2491
2492 # LOCALURL and FULLURL
2493 if ( !$found ) {
2494 $mwLocal =& MagicWord::get( MAG_LOCALURL );
2495 $mwLocalE =& MagicWord::get( MAG_LOCALURLE );
2496 $mwFull =& MagicWord::get( MAG_FULLURL );
2497 $mwFullE =& MagicWord::get( MAG_FULLURLE );
2498
2499
2500 if ( $mwLocal->matchStartAndRemove( $part1 ) ) {
2501 $func = 'getLocalURL';
2502 } elseif ( $mwLocalE->matchStartAndRemove( $part1 ) ) {
2503 $func = 'escapeLocalURL';
2504 } elseif ( $mwFull->matchStartAndRemove( $part1 ) ) {
2505 $func = 'getFullURL';
2506 } elseif ( $mwFullE->matchStartAndRemove( $part1 ) ) {
2507 $func = 'escapeFullURL';
2508 } else {
2509 $func = false;
2510 }
2511
2512 if ( $func !== false ) {
2513 $title = Title::newFromText( $part1 );
2514 if ( !is_null( $title ) ) {
2515 if ( $argc > 0 ) {
2516 $text = $linestart . $title->$func( $args[0] );
2517 } else {
2518 $text = $linestart . $title->$func();
2519 }
2520 $found = true;
2521 }
2522 }
2523 }
2524
2525 # GRAMMAR
2526 if ( !$found && $argc == 1 ) {
2527 $mwGrammar =& MagicWord::get( MAG_GRAMMAR );
2528 if ( $mwGrammar->matchStartAndRemove( $part1 ) ) {
2529 $text = $linestart . $wgContLang->convertGrammar( $args[0], $part1 );
2530 $found = true;
2531 }
2532 }
2533
2534 # PLURAL
2535 if ( !$found && $argc >= 2 ) {
2536 $mwPluralForm =& MagicWord::get( MAG_PLURAL );
2537 if ( $mwPluralForm->matchStartAndRemove( $part1 ) ) {
2538 if ($argc==2) {$args[2]=$args[1];}
2539 $text = $linestart . $wgContLang->convertPlural( $part1, $args[0], $args[1], $args[2]);
2540 $found = true;
2541 }
2542 }
2543
2544 # Template table test
2545
2546 # Did we encounter this template already? If yes, it is in the cache
2547 # and we need to check for loops.
2548 if ( !$found && isset( $this->mTemplates[$piece['title']] ) ) {
2549 $found = true;
2550
2551 # Infinite loop test
2552 if ( isset( $this->mTemplatePath[$part1] ) ) {
2553 $noparse = true;
2554 $noargs = true;
2555 $found = true;
2556 $text = $linestart .
2557 '{{' . $part1 . '}}' .
2558 '<!-- WARNING: template loop detected -->';
2559 wfDebug( "$fname: template loop broken at '$part1'\n" );
2560 } else {
2561 # set $text to cached message.
2562 $text = $linestart . $this->mTemplates[$piece['title']];
2563 }
2564 }
2565
2566 # Load from database
2567 $lastPathLevel = $this->mTemplatePath;
2568 if ( !$found ) {
2569 $ns = NS_TEMPLATE;
2570 $part1 = $this->maybeDoSubpageLink( $part1, $subpage='' );
2571 if ($subpage !== '') {
2572 $ns = $this->mTitle->getNamespace();
2573 }
2574 $title = Title::newFromText( $part1, $ns );
2575
2576 if ( !is_null( $title ) ) {
2577 if ( !$title->isExternal() ) {
2578 # Check for excessive inclusion
2579 $dbk = $title->getPrefixedDBkey();
2580 if ( $this->incrementIncludeCount( $dbk ) ) {
2581 if ( $title->getNamespace() == NS_SPECIAL && $this->mOptions->getAllowSpecialInclusion() ) {
2582 # Capture special page output
2583 $text = SpecialPage::capturePath( $title );
2584 if ( is_string( $text ) ) {
2585 $found = true;
2586 $noparse = true;
2587 $noargs = true;
2588 $isHTML = true;
2589 $this->disableCache();
2590 }
2591 } else {
2592 $articleContent = $this->fetchTemplate( $title );
2593 if ( $articleContent !== false ) {
2594 $found = true;
2595 $text = $articleContent;
2596 $replaceHeadings = true;
2597 }
2598 }
2599 }
2600
2601 # If the title is valid but undisplayable, make a link to it
2602 if ( $this->mOutputType == OT_HTML && !$found ) {
2603 $text = '[['.$title->getPrefixedText().']]';
2604 $found = true;
2605 }
2606 } elseif ( $title->isTrans() ) {
2607 // Interwiki transclusion
2608 if ( $this->mOutputType == OT_HTML && !$forceRawInterwiki ) {
2609 $text = $this->interwikiTransclude( $title, 'render' );
2610 $isHTML = true;
2611 $noparse = true;
2612 } else {
2613 $text = $this->interwikiTransclude( $title, 'raw' );
2614 $replaceHeadings = true;
2615 }
2616 $found = true;
2617 }
2618
2619 # Template cache array insertion
2620 # Use the original $piece['title'] not the mangled $part1, so that
2621 # modifiers such as RAW: produce separate cache entries
2622 if( $found ) {
2623 $this->mTemplates[$piece['title']] = $text;
2624 $text = $linestart . $text;
2625 }
2626 }
2627 }
2628
2629 # Recursive parsing, escaping and link table handling
2630 # Only for HTML output
2631 if ( $nowiki && $found && $this->mOutputType == OT_HTML ) {
2632 $text = wfEscapeWikiText( $text );
2633 } elseif ( ($this->mOutputType == OT_HTML || $this->mOutputType == OT_WIKI) && $found ) {
2634 if ( !$noargs ) {
2635 # Clean up argument array
2636 $assocArgs = array();
2637 $index = 1;
2638 foreach( $args as $arg ) {
2639 $eqpos = strpos( $arg, '=' );
2640 if ( $eqpos === false ) {
2641 $assocArgs[$index++] = $arg;
2642 } else {
2643 $name = trim( substr( $arg, 0, $eqpos ) );
2644 $value = trim( substr( $arg, $eqpos+1 ) );
2645 if ( $value === false ) {
2646 $value = '';
2647 }
2648 if ( $name !== false ) {
2649 $assocArgs[$name] = $value;
2650 }
2651 }
2652 }
2653
2654 # Add a new element to the templace recursion path
2655 $this->mTemplatePath[$part1] = 1;
2656 }
2657
2658 if ( !$noparse ) {
2659 # If there are any <onlyinclude> tags, only include them
2660 if ( in_string( '<onlyinclude>', $text ) && in_string( '</onlyinclude>', $text ) ) {
2661 preg_match_all( '/<onlyinclude>(.*?)\n?<\/onlyinclude>/s', $text, $m );
2662 $text = '';
2663 foreach ($m[1] as $piece)
2664 $text .= $piece;
2665 }
2666 # Remove <noinclude> sections and <includeonly> tags
2667 $text = preg_replace( '/<noinclude>.*?<\/noinclude>/s', '', $text );
2668 $text = strtr( $text, array( '<includeonly>' => '' , '</includeonly>' => '' ) );
2669
2670 if( $this->mOutputType == OT_HTML ) {
2671 # Strip <nowiki>, <pre>, etc.
2672 $text = $this->strip( $text, $this->mStripState );
2673 $text = Sanitizer::removeHTMLtags( $text, array( &$this, 'replaceVariables' ), $assocArgs );
2674 }
2675 $text = $this->replaceVariables( $text, $assocArgs );
2676
2677 # If the template begins with a table or block-level
2678 # element, it should be treated as beginning a new line.
2679 if (!$piece['lineStart'] && preg_match('/^({\\||:|;|#|\*)/', $text)) {
2680 $text = "\n" . $text;
2681 }
2682 } elseif ( !$noargs ) {
2683 # $noparse and !$noargs
2684 # Just replace the arguments, not any double-brace items
2685 # This is used for rendered interwiki transclusion
2686 $text = $this->replaceVariables( $text, $assocArgs, true );
2687 }
2688 }
2689 # Prune lower levels off the recursion check path
2690 $this->mTemplatePath = $lastPathLevel;
2691
2692 if ( !$found ) {
2693 wfProfileOut( $fname );
2694 return $piece['text'];
2695 } else {
2696 if ( $isHTML ) {
2697 # Replace raw HTML by a placeholder
2698 # Add a blank line preceding, to prevent it from mucking up
2699 # immediately preceding headings
2700 $text = "\n\n" . $this->insertStripItem( $text, $this->mStripState );
2701 } else {
2702 # replace ==section headers==
2703 # XXX this needs to go away once we have a better parser.
2704 if ( $this->mOutputType != OT_WIKI && $replaceHeadings ) {
2705 if( !is_null( $title ) )
2706 $encodedname = base64_encode($title->getPrefixedDBkey());
2707 else
2708 $encodedname = base64_encode("");
2709 $m = preg_split('/(^={1,6}.*?={1,6}\s*?$)/m', $text, -1,
2710 PREG_SPLIT_DELIM_CAPTURE);
2711 $text = '';
2712 $nsec = 0;
2713 for( $i = 0; $i < count($m); $i += 2 ) {
2714 $text .= $m[$i];
2715 if (!isset($m[$i + 1]) || $m[$i + 1] == "") continue;
2716 $hl = $m[$i + 1];
2717 if( strstr($hl, "<!--MWTEMPLATESECTION") ) {
2718 $text .= $hl;
2719 continue;
2720 }
2721 preg_match('/^(={1,6})(.*?)(={1,6})\s*?$/m', $hl, $m2);
2722 $text .= $m2[1] . $m2[2] . "<!--MWTEMPLATESECTION="
2723 . $encodedname . "&" . base64_encode("$nsec") . "-->" . $m2[3];
2724
2725 $nsec++;
2726 }
2727 }
2728 }
2729 }
2730
2731 # Prune lower levels off the recursion check path
2732 $this->mTemplatePath = $lastPathLevel;
2733
2734 if ( !$found ) {
2735 wfProfileOut( $fname );
2736 return $piece['text'];
2737 } else {
2738 wfProfileOut( $fname );
2739 return $text;
2740 }
2741 }
2742
2743 /**
2744 * Fetch the unparsed text of a template and register a reference to it.
2745 */
2746 function fetchTemplate( $title ) {
2747 $text = false;
2748 // Loop to fetch the article, with up to 1 redirect
2749 for ( $i = 0; $i < 2 && is_object( $title ); $i++ ) {
2750 $rev = Revision::newFromTitle( $title );
2751 $this->mOutput->addTemplate( $title, $title->getArticleID() );
2752 if ( !$rev ) {
2753 break;
2754 }
2755 $text = $rev->getText();
2756 if ( $text === false ) {
2757 break;
2758 }
2759 // Redirect?
2760 $title = Title::newFromRedirect( $text );
2761 }
2762 return $text;
2763 }
2764
2765 /**
2766 * Transclude an interwiki link.
2767 */
2768 function interwikiTransclude( $title, $action ) {
2769 global $wgEnableScaryTranscluding, $wgCanonicalNamespaceNames;
2770
2771 if (!$wgEnableScaryTranscluding)
2772 return wfMsg('scarytranscludedisabled');
2773
2774 // The namespace will actually only be 0 or 10, depending on whether there was a leading :
2775 // But we'll handle it generally anyway
2776 if ( $title->getNamespace() ) {
2777 // Use the canonical namespace, which should work anywhere
2778 $articleName = $wgCanonicalNamespaceNames[$title->getNamespace()] . ':' . $title->getDBkey();
2779 } else {
2780 $articleName = $title->getDBkey();
2781 }
2782
2783 $url = str_replace('$1', urlencode($articleName), Title::getInterwikiLink($title->getInterwiki()));
2784 $url .= "?action=$action";
2785 if (strlen($url) > 255)
2786 return wfMsg('scarytranscludetoolong');
2787 return $this->fetchScaryTemplateMaybeFromCache($url);
2788 }
2789
2790 function fetchScaryTemplateMaybeFromCache($url) {
2791 global $wgTranscludeCacheExpiry;
2792 $dbr =& wfGetDB(DB_SLAVE);
2793 $obj = $dbr->selectRow('transcache', array('tc_time', 'tc_contents'),
2794 array('tc_url' => $url));
2795 if ($obj) {
2796 $time = $obj->tc_time;
2797 $text = $obj->tc_contents;
2798 if ($time && time() < $time + $wgTranscludeCacheExpiry ) {
2799 return $text;
2800 }
2801 }
2802
2803 $text = wfGetHTTP($url);
2804 if (!$text)
2805 return wfMsg('scarytranscludefailed', $url);
2806
2807 $dbw =& wfGetDB(DB_MASTER);
2808 $dbw->replace('transcache', array('tc_url'), array(
2809 'tc_url' => $url,
2810 'tc_time' => time(),
2811 'tc_contents' => $text));
2812 return $text;
2813 }
2814
2815
2816 /**
2817 * Triple brace replacement -- used for template arguments
2818 * @access private
2819 */
2820 function argSubstitution( $matches ) {
2821 $arg = trim( $matches['title'] );
2822 $text = $matches['text'];
2823 $inputArgs = end( $this->mArgStack );
2824
2825 if ( array_key_exists( $arg, $inputArgs ) ) {
2826 $text = $inputArgs[$arg];
2827 } else if ($this->mOutputType == OT_HTML && null != $matches['parts'] && count($matches['parts']) > 0) {
2828 $text = $matches['parts'][0];
2829 }
2830
2831 return $text;
2832 }
2833
2834 /**
2835 * Returns true if the function is allowed to include this entity
2836 * @access private
2837 */
2838 function incrementIncludeCount( $dbk ) {
2839 if ( !array_key_exists( $dbk, $this->mIncludeCount ) ) {
2840 $this->mIncludeCount[$dbk] = 0;
2841 }
2842 if ( ++$this->mIncludeCount[$dbk] <= MAX_INCLUDE_REPEAT ) {
2843 return true;
2844 } else {
2845 return false;
2846 }
2847 }
2848
2849 /**
2850 * This function accomplishes several tasks:
2851 * 1) Auto-number headings if that option is enabled
2852 * 2) Add an [edit] link to sections for logged in users who have enabled the option
2853 * 3) Add a Table of contents on the top for users who have enabled the option
2854 * 4) Auto-anchor headings
2855 *
2856 * It loops through all headlines, collects the necessary data, then splits up the
2857 * string and re-inserts the newly formatted headlines.
2858 *
2859 * @param string $text
2860 * @param boolean $isMain
2861 * @access private
2862 */
2863 function formatHeadings( $text, $isMain=true ) {
2864 global $wgMaxTocLevel, $wgContLang;
2865
2866 $doNumberHeadings = $this->mOptions->getNumberHeadings();
2867 $doShowToc = true;
2868 $forceTocHere = false;
2869 if( !$this->mTitle->userCanEdit() ) {
2870 $showEditLink = 0;
2871 } else {
2872 $showEditLink = $this->mOptions->getEditSection();
2873 }
2874
2875 # Inhibit editsection links if requested in the page
2876 $esw =& MagicWord::get( MAG_NOEDITSECTION );
2877 if( $esw->matchAndRemove( $text ) ) {
2878 $showEditLink = 0;
2879 }
2880 # if the string __NOTOC__ (not case-sensitive) occurs in the HTML,
2881 # do not add TOC
2882 $mw =& MagicWord::get( MAG_NOTOC );
2883 if( $mw->matchAndRemove( $text ) ) {
2884 $doShowToc = false;
2885 }
2886
2887 # Get all headlines for numbering them and adding funky stuff like [edit]
2888 # links - this is for later, but we need the number of headlines right now
2889 $numMatches = preg_match_all( '/<H([1-6])(.*?'.'>)(.*?)<\/H[1-6] *>/i', $text, $matches );
2890
2891 # if there are fewer than 4 headlines in the article, do not show TOC
2892 if( $numMatches < 4 ) {
2893 $doShowToc = false;
2894 }
2895
2896 # if the string __TOC__ (not case-sensitive) occurs in the HTML,
2897 # override above conditions and always show TOC at that place
2898
2899 $mw =& MagicWord::get( MAG_TOC );
2900 if($mw->match( $text ) ) {
2901 $doShowToc = true;
2902 $forceTocHere = true;
2903 } else {
2904 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
2905 # override above conditions and always show TOC above first header
2906 $mw =& MagicWord::get( MAG_FORCETOC );
2907 if ($mw->matchAndRemove( $text ) ) {
2908 $doShowToc = true;
2909 }
2910 }
2911
2912 # Never ever show TOC if no headers
2913 if( $numMatches < 1 ) {
2914 $doShowToc = false;
2915 }
2916
2917 # We need this to perform operations on the HTML
2918 $sk =& $this->mOptions->getSkin();
2919
2920 # headline counter
2921 $headlineCount = 0;
2922 $sectionCount = 0; # headlineCount excluding template sections
2923
2924 # Ugh .. the TOC should have neat indentation levels which can be
2925 # passed to the skin functions. These are determined here
2926 $toc = '';
2927 $full = '';
2928 $head = array();
2929 $sublevelCount = array();
2930 $levelCount = array();
2931 $toclevel = 0;
2932 $level = 0;
2933 $prevlevel = 0;
2934 $toclevel = 0;
2935 $prevtoclevel = 0;
2936
2937 foreach( $matches[3] as $headline ) {
2938 $istemplate = 0;
2939 $templatetitle = '';
2940 $templatesection = 0;
2941 $numbering = '';
2942
2943 if (preg_match("/<!--MWTEMPLATESECTION=([^&]+)&([^_]+)-->/", $headline, $mat)) {
2944 $istemplate = 1;
2945 $templatetitle = base64_decode($mat[1]);
2946 $templatesection = 1 + (int)base64_decode($mat[2]);
2947 $headline = preg_replace("/<!--MWTEMPLATESECTION=([^&]+)&([^_]+)-->/", "", $headline);
2948 }
2949
2950 if( $toclevel ) {
2951 $prevlevel = $level;
2952 $prevtoclevel = $toclevel;
2953 }
2954 $level = $matches[1][$headlineCount];
2955
2956 if( $doNumberHeadings || $doShowToc ) {
2957
2958 if ( $level > $prevlevel ) {
2959 # Increase TOC level
2960 $toclevel++;
2961 $sublevelCount[$toclevel] = 0;
2962 $toc .= $sk->tocIndent();
2963 }
2964 elseif ( $level < $prevlevel && $toclevel > 1 ) {
2965 # Decrease TOC level, find level to jump to
2966
2967 if ( $toclevel == 2 && $level <= $levelCount[1] ) {
2968 # Can only go down to level 1
2969 $toclevel = 1;
2970 } else {
2971 for ($i = $toclevel; $i > 0; $i--) {
2972 if ( $levelCount[$i] == $level ) {
2973 # Found last matching level
2974 $toclevel = $i;
2975 break;
2976 }
2977 elseif ( $levelCount[$i] < $level ) {
2978 # Found first matching level below current level
2979 $toclevel = $i + 1;
2980 break;
2981 }
2982 }
2983 }
2984
2985 $toc .= $sk->tocUnindent( $prevtoclevel - $toclevel );
2986 }
2987 else {
2988 # No change in level, end TOC line
2989 $toc .= $sk->tocLineEnd();
2990 }
2991
2992 $levelCount[$toclevel] = $level;
2993
2994 # count number of headlines for each level
2995 @$sublevelCount[$toclevel]++;
2996 $dot = 0;
2997 for( $i = 1; $i <= $toclevel; $i++ ) {
2998 if( !empty( $sublevelCount[$i] ) ) {
2999 if( $dot ) {
3000 $numbering .= '.';
3001 }
3002 $numbering .= $wgContLang->formatNum( $sublevelCount[$i] );
3003 $dot = 1;
3004 }
3005 }
3006 }
3007
3008 # The canonized header is a version of the header text safe to use for links
3009 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
3010 $canonized_headline = $this->unstrip( $headline, $this->mStripState );
3011 $canonized_headline = $this->unstripNoWiki( $canonized_headline, $this->mStripState );
3012
3013 # Remove link placeholders by the link text.
3014 # <!--LINK number-->
3015 # turns into
3016 # link text with suffix
3017 $canonized_headline = preg_replace( '/<!--LINK ([0-9]*)-->/e',
3018 "\$this->mLinkHolders['texts'][\$1]",
3019 $canonized_headline );
3020 $canonized_headline = preg_replace( '/<!--IWLINK ([0-9]*)-->/e',
3021 "\$this->mInterwikiLinkHolders['texts'][\$1]",
3022 $canonized_headline );
3023
3024 # strip out HTML
3025 $canonized_headline = preg_replace( '/<.*?' . '>/','',$canonized_headline );
3026 $tocline = trim( $canonized_headline );
3027 $canonized_headline = Sanitizer::escapeId( $tocline );
3028 $refers[$headlineCount] = $canonized_headline;
3029
3030 # count how many in assoc. array so we can track dupes in anchors
3031 @$refers[$canonized_headline]++;
3032 $refcount[$headlineCount]=$refers[$canonized_headline];
3033
3034 # Don't number the heading if it is the only one (looks silly)
3035 if( $doNumberHeadings && count( $matches[3] ) > 1) {
3036 # the two are different if the line contains a link
3037 $headline=$numbering . ' ' . $headline;
3038 }
3039
3040 # Create the anchor for linking from the TOC to the section
3041 $anchor = $canonized_headline;
3042 if($refcount[$headlineCount] > 1 ) {
3043 $anchor .= '_' . $refcount[$headlineCount];
3044 }
3045 if( $doShowToc && ( !isset($wgMaxTocLevel) || $toclevel<$wgMaxTocLevel ) ) {
3046 $toc .= $sk->tocLine($anchor, $tocline, $numbering, $toclevel);
3047 }
3048 if( $showEditLink && ( !$istemplate || $templatetitle !== "" ) ) {
3049 if ( empty( $head[$headlineCount] ) ) {
3050 $head[$headlineCount] = '';
3051 }
3052 if( $istemplate )
3053 $head[$headlineCount] .= $sk->editSectionLinkForOther($templatetitle, $templatesection);
3054 else
3055 $head[$headlineCount] .= $sk->editSectionLink($this->mTitle, $sectionCount+1);
3056 }
3057
3058 # give headline the correct <h#> tag
3059 @$head[$headlineCount] .= "<a name=\"$anchor\"></a><h".$level.$matches[2][$headlineCount] .$headline.'</h'.$level.'>';
3060
3061 $headlineCount++;
3062 if( !$istemplate )
3063 $sectionCount++;
3064 }
3065
3066 if( $doShowToc ) {
3067 $toc .= $sk->tocUnindent( $toclevel - 1 );
3068 $toc = $sk->tocList( $toc );
3069 }
3070
3071 # split up and insert constructed headlines
3072
3073 $blocks = preg_split( '/<H[1-6].*?' . '>.*?<\/H[1-6]>/i', $text );
3074 $i = 0;
3075
3076 foreach( $blocks as $block ) {
3077 if( $showEditLink && $headlineCount > 0 && $i == 0 && $block != "\n" ) {
3078 # This is the [edit] link that appears for the top block of text when
3079 # section editing is enabled
3080
3081 # Disabled because it broke block formatting
3082 # For example, a bullet point in the top line
3083 # $full .= $sk->editSectionLink(0);
3084 }
3085 $full .= $block;
3086 if( $doShowToc && !$i && $isMain && !$forceTocHere) {
3087 # Top anchor now in skin
3088 $full = $full.$toc;
3089 }
3090
3091 if( !empty( $head[$i] ) ) {
3092 $full .= $head[$i];
3093 }
3094 $i++;
3095 }
3096 if($forceTocHere) {
3097 $mw =& MagicWord::get( MAG_TOC );
3098 return $mw->replace( $toc, $full );
3099 } else {
3100 return $full;
3101 }
3102 }
3103
3104 /**
3105 * Return an HTML link for the "ISBN 123456" text
3106 * @access private
3107 */
3108 function magicISBN( $text ) {
3109 $fname = 'Parser::magicISBN';
3110 wfProfileIn( $fname );
3111
3112 $a = split( 'ISBN ', ' '.$text );
3113 if ( count ( $a ) < 2 ) {
3114 wfProfileOut( $fname );
3115 return $text;
3116 }
3117 $text = substr( array_shift( $a ), 1);
3118 $valid = '0123456789-Xx';
3119
3120 foreach ( $a as $x ) {
3121 $isbn = $blank = '' ;
3122 while ( ' ' == $x{0} ) {
3123 $blank .= ' ';
3124 $x = substr( $x, 1 );
3125 }
3126 if ( $x == '' ) { # blank isbn
3127 $text .= "ISBN $blank";
3128 continue;
3129 }
3130 while ( strstr( $valid, $x{0} ) != false ) {
3131 $isbn .= $x{0};
3132 $x = substr( $x, 1 );
3133 }
3134 $num = str_replace( '-', '', $isbn );
3135 $num = str_replace( ' ', '', $num );
3136 $num = str_replace( 'x', 'X', $num );
3137
3138 if ( '' == $num ) {
3139 $text .= "ISBN $blank$x";
3140 } else {
3141 $titleObj = Title::makeTitle( NS_SPECIAL, 'Booksources' );
3142 $text .= '<a href="' .
3143 $titleObj->escapeLocalUrl( 'isbn='.$num ) .
3144 "\" class=\"internal\">ISBN $isbn</a>";
3145 $text .= $x;
3146 }
3147 }
3148 wfProfileOut( $fname );
3149 return $text;
3150 }
3151
3152 /**
3153 * Return an HTML link for the "RFC 1234" text
3154 *
3155 * @access private
3156 * @param string $text Text to be processed
3157 * @param string $keyword Magic keyword to use (default RFC)
3158 * @param string $urlmsg Interface message to use (default rfcurl)
3159 * @return string
3160 */
3161 function magicRFC( $text, $keyword='RFC ', $urlmsg='rfcurl' ) {
3162
3163 $valid = '0123456789';
3164 $internal = false;
3165
3166 $a = split( $keyword, ' '.$text );
3167 if ( count ( $a ) < 2 ) {
3168 return $text;
3169 }
3170 $text = substr( array_shift( $a ), 1);
3171
3172 /* Check if keyword is preceed by [[.
3173 * This test is made here cause of the array_shift above
3174 * that prevent the test to be done in the foreach.
3175 */
3176 if ( substr( $text, -2 ) == '[[' ) {
3177 $internal = true;
3178 }
3179
3180 foreach ( $a as $x ) {
3181 /* token might be empty if we have RFC RFC 1234 */
3182 if ( $x=='' ) {
3183 $text.=$keyword;
3184 continue;
3185 }
3186
3187 $id = $blank = '' ;
3188
3189 /** remove and save whitespaces in $blank */
3190 while ( $x{0} == ' ' ) {
3191 $blank .= ' ';
3192 $x = substr( $x, 1 );
3193 }
3194
3195 /** remove and save the rfc number in $id */
3196 while ( strstr( $valid, $x{0} ) != false ) {
3197 $id .= $x{0};
3198 $x = substr( $x, 1 );
3199 }
3200
3201 if ( $id == '' ) {
3202 /* call back stripped spaces*/
3203 $text .= $keyword.$blank.$x;
3204 } elseif( $internal ) {
3205 /* normal link */
3206 $text .= $keyword.$id.$x;
3207 } else {
3208 /* build the external link*/
3209 $url = wfMsg( $urlmsg, $id);
3210 $sk =& $this->mOptions->getSkin();
3211 $la = $sk->getExternalLinkAttributes( $url, $keyword.$id );
3212 $text .= "<a href='{$url}'{$la}>{$keyword}{$id}</a>{$x}";
3213 }
3214
3215 /* Check if the next RFC keyword is preceed by [[ */
3216 $internal = ( substr($x,-2) == '[[' );
3217 }
3218 return $text;
3219 }
3220
3221 /**
3222 * Transform wiki markup when saving a page by doing \r\n -> \n
3223 * conversion, substitting signatures, {{subst:}} templates, etc.
3224 *
3225 * @param string $text the text to transform
3226 * @param Title &$title the Title object for the current article
3227 * @param User &$user the User object describing the current user
3228 * @param ParserOptions $options parsing options
3229 * @param bool $clearState whether to clear the parser state first
3230 * @return string the altered wiki markup
3231 * @access public
3232 */
3233 function preSaveTransform( $text, &$title, &$user, $options, $clearState = true ) {
3234 $this->mOptions = $options;
3235 $this->mTitle =& $title;
3236 $this->mOutputType = OT_WIKI;
3237
3238 if ( $clearState ) {
3239 $this->clearState();
3240 }
3241
3242 $stripState = false;
3243 $pairs = array(
3244 "\r\n" => "\n",
3245 );
3246 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
3247 $text = $this->strip( $text, $stripState, true );
3248 $text = $this->pstPass2( $text, $user );
3249 $text = $this->unstrip( $text, $stripState );
3250 $text = $this->unstripNoWiki( $text, $stripState );
3251 return $text;
3252 }
3253
3254 /**
3255 * Pre-save transform helper function
3256 * @access private
3257 */
3258 function pstPass2( $text, &$user ) {
3259 global $wgContLang, $wgLocaltimezone;
3260
3261 /* Note: This is the timestamp saved as hardcoded wikitext to
3262 * the database, we use $wgContLang here in order to give
3263 * everyone the same signiture and use the default one rather
3264 * than the one selected in each users preferences.
3265 */
3266 if ( isset( $wgLocaltimezone ) ) {
3267 $oldtz = getenv( 'TZ' );
3268 putenv( 'TZ='.$wgLocaltimezone );
3269 }
3270 $d = $wgContLang->timeanddate( date( 'YmdHis' ), false, false) .
3271 ' (' . date( 'T' ) . ')';
3272 if ( isset( $wgLocaltimezone ) ) {
3273 putenv( 'TZ='.$oldtz );
3274 }
3275
3276 # Variable replacement
3277 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
3278 $text = $this->replaceVariables( $text );
3279
3280 # Signatures
3281 $sigText = $this->getUserSig( $user );
3282 $text = strtr( $text, array(
3283 '~~~~~' => $d,
3284 '~~~~' => "$sigText $d",
3285 '~~~' => $sigText
3286 ) );
3287
3288 # Context links: [[|name]] and [[name (context)|]]
3289 #
3290 global $wgLegalTitleChars;
3291 $tc = "[$wgLegalTitleChars]";
3292 $np = str_replace( array( '(', ')' ), array( '', '' ), $tc ); # No parens
3293
3294 $namespacechar = '[ _0-9A-Za-z\x80-\xff]'; # Namespaces can use non-ascii!
3295 $conpat = "/^({$np}+) \\(({$tc}+)\\)$/";
3296
3297 $p1 = "/\[\[({$np}+) \\(({$np}+)\\)\\|]]/"; # [[page (context)|]]
3298 $p2 = "/\[\[\\|({$tc}+)]]/"; # [[|page]]
3299 $p3 = "/\[\[(:*$namespacechar+):({$np}+)\\|]]/"; # [[namespace:page|]] and [[:namespace:page|]]
3300 $p4 = "/\[\[(:*$namespacechar+):({$np}+) \\(({$np}+)\\)\\|]]/"; # [[ns:page (cont)|]] and [[:ns:page (cont)|]]
3301 $context = '';
3302 $t = $this->mTitle->getText();
3303 if ( preg_match( $conpat, $t, $m ) ) {
3304 $context = $m[2];
3305 }
3306 $text = preg_replace( $p4, '[[\\1:\\2 (\\3)|\\2]]', $text );
3307 $text = preg_replace( $p1, '[[\\1 (\\2)|\\1]]', $text );
3308 $text = preg_replace( $p3, '[[\\1:\\2|\\2]]', $text );
3309
3310 if ( '' == $context ) {
3311 $text = preg_replace( $p2, '[[\\1]]', $text );
3312 } else {
3313 $text = preg_replace( $p2, "[[\\1 ({$context})|\\1]]", $text );
3314 }
3315
3316 # Trim trailing whitespace
3317 # MAG_END (__END__) tag allows for trailing
3318 # whitespace to be deliberately included
3319 $text = rtrim( $text );
3320 $mw =& MagicWord::get( MAG_END );
3321 $mw->matchAndRemove( $text );
3322
3323 return $text;
3324 }
3325
3326 /**
3327 * Fetch the user's signature text, if any, and normalize to
3328 * validated, ready-to-insert wikitext.
3329 *
3330 * @param User $user
3331 * @return string
3332 * @access private
3333 */
3334 function getUserSig( &$user ) {
3335 global $wgContLang;
3336
3337 $username = $user->getName();
3338 $nickname = $user->getOption( 'nickname' );
3339 $nickname = $nickname === '' ? $username : $nickname;
3340
3341 if( $user->getBoolOption( 'fancysig' ) !== false ) {
3342 # Sig. might contain markup; validate this
3343 if( $this->validateSig( $nickname ) !== false ) {
3344 # Validated; clean up (if needed) and return it
3345 return( $this->cleanSig( $nickname ) );
3346 } else {
3347 # Failed to validate; fall back to the default
3348 $nickname = $username;
3349 wfDebug( "Parser::getUserSig: $username has bad XML tags in signature.\n" );
3350 }
3351 }
3352
3353 # If we're still here, make it a link to the user page
3354 $userpage = $user->getUserPage();
3355 return( '[[' . $userpage->getPrefixedText() . '|' . wfEscapeWikiText( $nickname ) . ']]' );
3356 }
3357
3358 /**
3359 * Check that the user's signature contains no bad XML
3360 *
3361 * @param string $text
3362 * @return mixed An expanded string, or false if invalid.
3363 */
3364 function validateSig( $text ) {
3365 return( wfIsWellFormedXmlFragment( $text ) ? $text : false );
3366 }
3367
3368 /**
3369 * Clean up signature text
3370 *
3371 * 1) Strip ~~~, ~~~~ and ~~~~~ out of signatures
3372 * 2) Substitute all transclusions
3373 *
3374 * @param string $text
3375 * @return string Signature text
3376 */
3377 function cleanSig( $text ) {
3378 $substWord = MagicWord::get( MAG_SUBST );
3379 $substRegex = '/\{\{(?!(?:' . $substWord->getBaseRegex() . '))/x' . $substWord->getRegexCase();
3380 $substText = '{{' . $substWord->getSynonym( 0 );
3381
3382 $text = preg_replace( $substRegex, $substText, $text );
3383 $text = preg_replace( '/~{3,5}/', '', $text );
3384 $text = $this->replaceVariables( $text );
3385
3386 return $text;
3387 }
3388
3389 /**
3390 * Set up some variables which are usually set up in parse()
3391 * so that an external function can call some class members with confidence
3392 * @access public
3393 */
3394 function startExternalParse( &$title, $options, $outputType, $clearState = true ) {
3395 $this->mTitle =& $title;
3396 $this->mOptions = $options;
3397 $this->mOutputType = $outputType;
3398 if ( $clearState ) {
3399 $this->clearState();
3400 }
3401 }
3402
3403 /**
3404 * Transform a MediaWiki message by replacing magic variables.
3405 *
3406 * @param string $text the text to transform
3407 * @param ParserOptions $options options
3408 * @return string the text with variables substituted
3409 * @access public
3410 */
3411 function transformMsg( $text, $options ) {
3412 global $wgTitle;
3413 static $executing = false;
3414
3415 $fname = "Parser::transformMsg";
3416
3417 # Guard against infinite recursion
3418 if ( $executing ) {
3419 return $text;
3420 }
3421 $executing = true;
3422
3423 wfProfileIn($fname);
3424
3425 $this->mTitle = $wgTitle;
3426 $this->mOptions = $options;
3427 $this->mOutputType = OT_MSG;
3428 $this->clearState();
3429 $text = $this->replaceVariables( $text );
3430
3431 $executing = false;
3432 wfProfileOut($fname);
3433 return $text;
3434 }
3435
3436 /**
3437 * Create an HTML-style tag, e.g. <yourtag>special text</yourtag>
3438 * Callback will be called with the text within
3439 * Transform and return the text within
3440 *
3441 * @access public
3442 *
3443 * @param mixed $tag The tag to use, e.g. 'hook' for <hook>
3444 * @param mixed $callback The callback function (and object) to use for the tag
3445 *
3446 * @return The old value of the mTagHooks array associated with the hook
3447 */
3448 function setHook( $tag, $callback ) {
3449 $oldVal = @$this->mTagHooks[$tag];
3450 $this->mTagHooks[$tag] = $callback;
3451
3452 return $oldVal;
3453 }
3454
3455 /**
3456 * Replace <!--LINK--> link placeholders with actual links, in the buffer
3457 * Placeholders created in Skin::makeLinkObj()
3458 * Returns an array of links found, indexed by PDBK:
3459 * 0 - broken
3460 * 1 - normal link
3461 * 2 - stub
3462 * $options is a bit field, RLH_FOR_UPDATE to select for update
3463 */
3464 function replaceLinkHolders( &$text, $options = 0 ) {
3465 global $wgUser;
3466 global $wgOutputReplace;
3467
3468 $fname = 'Parser::replaceLinkHolders';
3469 wfProfileIn( $fname );
3470
3471 $pdbks = array();
3472 $colours = array();
3473 $sk =& $this->mOptions->getSkin();
3474 $linkCache =& LinkCache::singleton();
3475
3476 if ( !empty( $this->mLinkHolders['namespaces'] ) ) {
3477 wfProfileIn( $fname.'-check' );
3478 $dbr =& wfGetDB( DB_SLAVE );
3479 $page = $dbr->tableName( 'page' );
3480 $threshold = $wgUser->getOption('stubthreshold');
3481
3482 # Sort by namespace
3483 asort( $this->mLinkHolders['namespaces'] );
3484
3485 # Generate query
3486 $query = false;
3487 foreach ( $this->mLinkHolders['namespaces'] as $key => $ns ) {
3488 # Make title object
3489 $title = $this->mLinkHolders['titles'][$key];
3490
3491 # Skip invalid entries.
3492 # Result will be ugly, but prevents crash.
3493 if ( is_null( $title ) ) {
3494 continue;
3495 }
3496 $pdbk = $pdbks[$key] = $title->getPrefixedDBkey();
3497
3498 # Check if it's a static known link, e.g. interwiki
3499 if ( $title->isAlwaysKnown() ) {
3500 $colours[$pdbk] = 1;
3501 } elseif ( ( $id = $linkCache->getGoodLinkID( $pdbk ) ) != 0 ) {
3502 $colours[$pdbk] = 1;
3503 $this->mOutput->addLink( $title, $id );
3504 } elseif ( $linkCache->isBadLink( $pdbk ) ) {
3505 $colours[$pdbk] = 0;
3506 } else {
3507 # Not in the link cache, add it to the query
3508 if ( !isset( $current ) ) {
3509 $current = $ns;
3510 $query = "SELECT page_id, page_namespace, page_title";
3511 if ( $threshold > 0 ) {
3512 $query .= ', page_len, page_is_redirect';
3513 }
3514 $query .= " FROM $page WHERE (page_namespace=$ns AND page_title IN(";
3515 } elseif ( $current != $ns ) {
3516 $current = $ns;
3517 $query .= ")) OR (page_namespace=$ns AND page_title IN(";
3518 } else {
3519 $query .= ', ';
3520 }
3521
3522 $query .= $dbr->addQuotes( $this->mLinkHolders['dbkeys'][$key] );
3523 }
3524 }
3525 if ( $query ) {
3526 $query .= '))';
3527 if ( $options & RLH_FOR_UPDATE ) {
3528 $query .= ' FOR UPDATE';
3529 }
3530
3531 $res = $dbr->query( $query, $fname );
3532
3533 # Fetch data and form into an associative array
3534 # non-existent = broken
3535 # 1 = known
3536 # 2 = stub
3537 while ( $s = $dbr->fetchObject($res) ) {
3538 $title = Title::makeTitle( $s->page_namespace, $s->page_title );
3539 $pdbk = $title->getPrefixedDBkey();
3540 $linkCache->addGoodLinkObj( $s->page_id, $title );
3541 $this->mOutput->addLink( $title, $s->page_id );
3542
3543 if ( $threshold > 0 ) {
3544 $size = $s->page_len;
3545 if ( $s->page_is_redirect || $s->page_namespace != 0 || $size >= $threshold ) {
3546 $colours[$pdbk] = 1;
3547 } else {
3548 $colours[$pdbk] = 2;
3549 }
3550 } else {
3551 $colours[$pdbk] = 1;
3552 }
3553 }
3554 }
3555 wfProfileOut( $fname.'-check' );
3556
3557 # Construct search and replace arrays
3558 wfProfileIn( $fname.'-construct' );
3559 $wgOutputReplace = array();
3560 foreach ( $this->mLinkHolders['namespaces'] as $key => $ns ) {
3561 $pdbk = $pdbks[$key];
3562 $searchkey = "<!--LINK $key-->";
3563 $title = $this->mLinkHolders['titles'][$key];
3564 if ( empty( $colours[$pdbk] ) ) {
3565 $linkCache->addBadLinkObj( $title );
3566 $colours[$pdbk] = 0;
3567 $this->mOutput->addLink( $title, 0 );
3568 $wgOutputReplace[$searchkey] = $sk->makeBrokenLinkObj( $title,
3569 $this->mLinkHolders['texts'][$key],
3570 $this->mLinkHolders['queries'][$key] );
3571 } elseif ( $colours[$pdbk] == 1 ) {
3572 $wgOutputReplace[$searchkey] = $sk->makeKnownLinkObj( $title,
3573 $this->mLinkHolders['texts'][$key],
3574 $this->mLinkHolders['queries'][$key] );
3575 } elseif ( $colours[$pdbk] == 2 ) {
3576 $wgOutputReplace[$searchkey] = $sk->makeStubLinkObj( $title,
3577 $this->mLinkHolders['texts'][$key],
3578 $this->mLinkHolders['queries'][$key] );
3579 }
3580 }
3581 wfProfileOut( $fname.'-construct' );
3582
3583 # Do the thing
3584 wfProfileIn( $fname.'-replace' );
3585
3586 $text = preg_replace_callback(
3587 '/(<!--LINK .*?-->)/',
3588 "wfOutputReplaceMatches",
3589 $text);
3590
3591 wfProfileOut( $fname.'-replace' );
3592 }
3593
3594 # Now process interwiki link holders
3595 # This is quite a bit simpler than internal links
3596 if ( !empty( $this->mInterwikiLinkHolders['texts'] ) ) {
3597 wfProfileIn( $fname.'-interwiki' );
3598 # Make interwiki link HTML
3599 $wgOutputReplace = array();
3600 foreach( $this->mInterwikiLinkHolders['texts'] as $key => $link ) {
3601 $title = $this->mInterwikiLinkHolders['titles'][$key];
3602 $wgOutputReplace[$key] = $sk->makeLinkObj( $title, $link );
3603 }
3604
3605 $text = preg_replace_callback(
3606 '/<!--IWLINK (.*?)-->/',
3607 "wfOutputReplaceMatches",
3608 $text );
3609 wfProfileOut( $fname.'-interwiki' );
3610 }
3611
3612 wfProfileOut( $fname );
3613 return $colours;
3614 }
3615
3616 /**
3617 * Replace <!--LINK--> link placeholders with plain text of links
3618 * (not HTML-formatted).
3619 * @param string $text
3620 * @return string
3621 */
3622 function replaceLinkHoldersText( $text ) {
3623 global $wgUser;
3624 global $wgOutputReplace;
3625
3626 $fname = 'Parser::replaceLinkHoldersText';
3627 wfProfileIn( $fname );
3628
3629 $text = preg_replace_callback(
3630 '/<!--(LINK|IWLINK) (.*?)-->/',
3631 array( &$this, 'replaceLinkHoldersTextCallback' ),
3632 $text );
3633
3634 wfProfileOut( $fname );
3635 return $text;
3636 }
3637
3638 /**
3639 * @param array $matches
3640 * @return string
3641 * @access private
3642 */
3643 function replaceLinkHoldersTextCallback( $matches ) {
3644 $type = $matches[1];
3645 $key = $matches[2];
3646 if( $type == 'LINK' ) {
3647 if( isset( $this->mLinkHolders['texts'][$key] ) ) {
3648 return $this->mLinkHolders['texts'][$key];
3649 }
3650 } elseif( $type == 'IWLINK' ) {
3651 if( isset( $this->mInterwikiLinkHolders['texts'][$key] ) ) {
3652 return $this->mInterwikiLinkHolders['texts'][$key];
3653 }
3654 }
3655 return $matches[0];
3656 }
3657
3658 /**
3659 * Renders an image gallery from a text with one line per image.
3660 * text labels may be given by using |-style alternative text. E.g.
3661 * Image:one.jpg|The number "1"
3662 * Image:tree.jpg|A tree
3663 * given as text will return the HTML of a gallery with two images,
3664 * labeled 'The number "1"' and
3665 * 'A tree'.
3666 */
3667 function renderImageGallery( $text ) {
3668 # Setup the parser
3669 $parserOptions = new ParserOptions;
3670 $localParser = new Parser();
3671
3672 $ig = new ImageGallery();
3673 $ig->setShowBytes( false );
3674 $ig->setShowFilename( false );
3675 $lines = explode( "\n", $text );
3676
3677 foreach ( $lines as $line ) {
3678 # match lines like these:
3679 # Image:someimage.jpg|This is some image
3680 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
3681 # Skip empty lines
3682 if ( count( $matches ) == 0 ) {
3683 continue;
3684 }
3685 $nt =& Title::newFromText( $matches[1] );
3686 if( is_null( $nt ) ) {
3687 # Bogus title. Ignore these so we don't bomb out later.
3688 continue;
3689 }
3690 if ( isset( $matches[3] ) ) {
3691 $label = $matches[3];
3692 } else {
3693 $label = '';
3694 }
3695
3696 $pout = $localParser->parse( $label , $this->mTitle, $parserOptions );
3697 $html = $pout->getText();
3698
3699 $ig->add( new Image( $nt ), $html );
3700 $this->mOutput->addImage( $nt->getDBkey() );
3701 }
3702 return $ig->toHTML();
3703 }
3704
3705 /**
3706 * Parse image options text and use it to make an image
3707 */
3708 function makeImage( &$nt, $options ) {
3709 global $wgContLang, $wgUseImageResize, $wgUser;
3710
3711 $align = '';
3712
3713 # Check if the options text is of the form "options|alt text"
3714 # Options are:
3715 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
3716 # * left no resizing, just left align. label is used for alt= only
3717 # * right same, but right aligned
3718 # * none same, but not aligned
3719 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
3720 # * center center the image
3721 # * framed Keep original image size, no magnify-button.
3722
3723 $part = explode( '|', $options);
3724
3725 $mwThumb =& MagicWord::get( MAG_IMG_THUMBNAIL );
3726 $mwManualThumb =& MagicWord::get( MAG_IMG_MANUALTHUMB );
3727 $mwLeft =& MagicWord::get( MAG_IMG_LEFT );
3728 $mwRight =& MagicWord::get( MAG_IMG_RIGHT );
3729 $mwNone =& MagicWord::get( MAG_IMG_NONE );
3730 $mwWidth =& MagicWord::get( MAG_IMG_WIDTH );
3731 $mwCenter =& MagicWord::get( MAG_IMG_CENTER );
3732 $mwFramed =& MagicWord::get( MAG_IMG_FRAMED );
3733 $caption = '';
3734
3735 $width = $height = $framed = $thumb = false;
3736 $manual_thumb = '' ;
3737
3738 foreach( $part as $key => $val ) {
3739 if ( $wgUseImageResize && ! is_null( $mwThumb->matchVariableStartToEnd($val) ) ) {
3740 $thumb=true;
3741 } elseif ( ! is_null( $match = $mwManualThumb->matchVariableStartToEnd($val) ) ) {
3742 # use manually specified thumbnail
3743 $thumb=true;
3744 $manual_thumb = $match;
3745 } elseif ( ! is_null( $mwRight->matchVariableStartToEnd($val) ) ) {
3746 # remember to set an alignment, don't render immediately
3747 $align = 'right';
3748 } elseif ( ! is_null( $mwLeft->matchVariableStartToEnd($val) ) ) {
3749 # remember to set an alignment, don't render immediately
3750 $align = 'left';
3751 } elseif ( ! is_null( $mwCenter->matchVariableStartToEnd($val) ) ) {
3752 # remember to set an alignment, don't render immediately
3753 $align = 'center';
3754 } elseif ( ! is_null( $mwNone->matchVariableStartToEnd($val) ) ) {
3755 # remember to set an alignment, don't render immediately
3756 $align = 'none';
3757 } elseif ( $wgUseImageResize && ! is_null( $match = $mwWidth->matchVariableStartToEnd($val) ) ) {
3758 wfDebug( "MAG_IMG_WIDTH match: $match\n" );
3759 # $match is the image width in pixels
3760 if ( preg_match( '/^([0-9]*)x([0-9]*)$/', $match, $m ) ) {
3761 $width = intval( $m[1] );
3762 $height = intval( $m[2] );
3763 } else {
3764 $width = intval($match);
3765 }
3766 } elseif ( ! is_null( $mwFramed->matchVariableStartToEnd($val) ) ) {
3767 $framed=true;
3768 } else {
3769 $caption = $val;
3770 }
3771 }
3772 # Strip bad stuff out of the alt text
3773 $alt = $this->replaceLinkHoldersText( $caption );
3774 $alt = Sanitizer::stripAllTags( $alt );
3775
3776 # Linker does the rest
3777 $sk =& $this->mOptions->getSkin();
3778 return $sk->makeImageLinkObj( $nt, $caption, $alt, $align, $width, $height, $framed, $thumb, $manual_thumb );
3779 }
3780
3781 /**
3782 * Set a flag in the output object indicating that the content is dynamic and
3783 * shouldn't be cached.
3784 */
3785 function disableCache() {
3786 $this->mOutput->mCacheTime = -1;
3787 }
3788
3789 /**#@+
3790 * Callback from the Sanitizer for expanding items found in HTML attribute
3791 * values, so they can be safely tested and escaped.
3792 * @param string $text
3793 * @param array $args
3794 * @return string
3795 * @access private
3796 */
3797 function attributeStripCallback( &$text, $args ) {
3798 $text = $this->replaceVariables( $text, $args );
3799 $text = $this->unstripForHTML( $text );
3800 return $text;
3801 }
3802
3803 function unstripForHTML( $text ) {
3804 $text = $this->unstrip( $text, $this->mStripState );
3805 $text = $this->unstripNoWiki( $text, $this->mStripState );
3806 return $text;
3807 }
3808 /**#@-*/
3809
3810 /**#@+
3811 * Accessor/mutator
3812 */
3813 function Title( $x = NULL ) { return wfSetVar( $this->mTitle, $x ); }
3814 function Options( $x = NULL ) { return wfSetVar( $this->mOptions, $x ); }
3815 function OutputType( $x = NULL ) { return wfSetVar( $this->mOutputType, $x ); }
3816 /**#@-*/
3817
3818 /**#@+
3819 * Accessor
3820 */
3821 function getTags() { return array_keys( $this->mTagHooks ); }
3822 /**#@-*/
3823 }
3824
3825 /**
3826 * @todo document
3827 * @package MediaWiki
3828 */
3829 class ParserOutput
3830 {
3831 var $mText, # The output text
3832 $mLanguageLinks, # List of the full text of language links, in the order they appear
3833 $mCategories, # Map of category names to sort keys
3834 $mContainsOldMagic, # Boolean variable indicating if the input contained variables like {{CURRENTDAY}}
3835 $mCacheTime, # Timestamp on this article, or -1 for uncacheable. Used in ParserCache.
3836 $mVersion, # Compatibility check
3837 $mTitleText, # title text of the chosen language variant
3838 $mLinks, # 2-D map of NS/DBK to ID for the links in the document. ID=zero for broken.
3839 $mTemplates, # 2-D map of NS/DBK to ID for the template references. ID=zero for broken.
3840 $mImages, # DB keys of the images used, in the array key only
3841 $mExternalLinks; # External link URLs, in the key only
3842
3843 function ParserOutput( $text = '', $languageLinks = array(), $categoryLinks = array(),
3844 $containsOldMagic = false, $titletext = '' )
3845 {
3846 $this->mText = $text;
3847 $this->mLanguageLinks = $languageLinks;
3848 $this->mCategories = $categoryLinks;
3849 $this->mContainsOldMagic = $containsOldMagic;
3850 $this->mCacheTime = '';
3851 $this->mVersion = MW_PARSER_VERSION;
3852 $this->mTitleText = $titletext;
3853 $this->mLinks = array();
3854 $this->mTemplates = array();
3855 $this->mImages = array();
3856 $this->mExternalLinks = array();
3857 }
3858
3859 function getText() { return $this->mText; }
3860 function getLanguageLinks() { return $this->mLanguageLinks; }
3861 function getCategoryLinks() { return array_keys( $this->mCategories ); }
3862 function &getCategories() { return $this->mCategories; }
3863 function getCacheTime() { return $this->mCacheTime; }
3864 function getTitleText() { return $this->mTitleText; }
3865 function &getLinks() { return $this->mLinks; }
3866 function &getTemplates() { return $this->mTemplates; }
3867 function &getImages() { return $this->mImages; }
3868 function &getExternalLinks() { return $this->mExternalLinks; }
3869
3870 function containsOldMagic() { return $this->mContainsOldMagic; }
3871 function setText( $text ) { return wfSetVar( $this->mText, $text ); }
3872 function setLanguageLinks( $ll ) { return wfSetVar( $this->mLanguageLinks, $ll ); }
3873 function setCategoryLinks( $cl ) { return wfSetVar( $this->mCategories, $cl ); }
3874 function setContainsOldMagic( $com ) { return wfSetVar( $this->mContainsOldMagic, $com ); }
3875 function setCacheTime( $t ) { return wfSetVar( $this->mCacheTime, $t ); }
3876 function setTitleText( $t ) { return wfSetVar ($this->mTitleText, $t); }
3877
3878 function addCategory( $c, $sort ) { $this->mCategories[$c] = $sort; }
3879 function addImage( $name ) { $this->mImages[$name] = 1; }
3880 function addLanguageLink( $t ) { $this->mLanguageLinks[] = $t; }
3881 function addExternalLink( $url ) { $this->mExternalLinks[$url] = 1; }
3882
3883 function addLink( $title, $id ) {
3884 $ns = $title->getNamespace();
3885 $dbk = $title->getDBkey();
3886 if ( !isset( $this->mLinks[$ns] ) ) {
3887 $this->mLinks[$ns] = array();
3888 }
3889 $this->mLinks[$ns][$dbk] = $id;
3890 }
3891
3892 function addTemplate( $title, $id ) {
3893 $ns = $title->getNamespace();
3894 $dbk = $title->getDBkey();
3895 if ( !isset( $this->mTemplates[$ns] ) ) {
3896 $this->mTemplates[$ns] = array();
3897 }
3898 $this->mTemplates[$ns][$dbk] = $id;
3899 }
3900
3901 /**
3902 * @deprecated
3903 */
3904 /*
3905 function merge( $other ) {
3906 $this->mLanguageLinks = array_merge( $this->mLanguageLinks, $other->mLanguageLinks );
3907 $this->mCategories = array_merge( $this->mCategories, $this->mLanguageLinks );
3908 $this->mContainsOldMagic = $this->mContainsOldMagic || $other->mContainsOldMagic;
3909 }*/
3910
3911 /**
3912 * Return true if this cached output object predates the global or
3913 * per-article cache invalidation timestamps, or if it comes from
3914 * an incompatible older version.
3915 *
3916 * @param string $touched the affected article's last touched timestamp
3917 * @return bool
3918 * @access public
3919 */
3920 function expired( $touched ) {
3921 global $wgCacheEpoch;
3922 return $this->getCacheTime() == -1 || // parser says it's uncacheable
3923 $this->getCacheTime() < $touched ||
3924 $this->getCacheTime() <= $wgCacheEpoch ||
3925 !isset( $this->mVersion ) ||
3926 version_compare( $this->mVersion, MW_PARSER_VERSION, "lt" );
3927 }
3928 }
3929
3930 /**
3931 * Set options of the Parser
3932 * @todo document
3933 * @package MediaWiki
3934 */
3935 class ParserOptions
3936 {
3937 # All variables are private
3938 var $mUseTeX; # Use texvc to expand <math> tags
3939 var $mUseDynamicDates; # Use DateFormatter to format dates
3940 var $mInterwikiMagic; # Interlanguage links are removed and returned in an array
3941 var $mAllowExternalImages; # Allow external images inline
3942 var $mAllowExternalImagesFrom; # If not, any exception?
3943 var $mSkin; # Reference to the preferred skin
3944 var $mDateFormat; # Date format index
3945 var $mEditSection; # Create "edit section" links
3946 var $mNumberHeadings; # Automatically number headings
3947 var $mAllowSpecialInclusion; # Allow inclusion of special pages
3948 var $mTidy; # Ask for tidy cleanup
3949
3950 function getUseTeX() { return $this->mUseTeX; }
3951 function getUseDynamicDates() { return $this->mUseDynamicDates; }
3952 function getInterwikiMagic() { return $this->mInterwikiMagic; }
3953 function getAllowExternalImages() { return $this->mAllowExternalImages; }
3954 function getAllowExternalImagesFrom() { return $this->mAllowExternalImagesFrom; }
3955 function &getSkin() { return $this->mSkin; }
3956 function getDateFormat() { return $this->mDateFormat; }
3957 function getEditSection() { return $this->mEditSection; }
3958 function getNumberHeadings() { return $this->mNumberHeadings; }
3959 function getAllowSpecialInclusion() { return $this->mAllowSpecialInclusion; }
3960 function getTidy() { return $this->mTidy; }
3961
3962 function setUseTeX( $x ) { return wfSetVar( $this->mUseTeX, $x ); }
3963 function setUseDynamicDates( $x ) { return wfSetVar( $this->mUseDynamicDates, $x ); }
3964 function setInterwikiMagic( $x ) { return wfSetVar( $this->mInterwikiMagic, $x ); }
3965 function setAllowExternalImages( $x ) { return wfSetVar( $this->mAllowExternalImages, $x ); }
3966 function setAllowExternalImagesFrom( $x ) { return wfSetVar( $this->mAllowExternalImagesFrom, $x ); }
3967 function setDateFormat( $x ) { return wfSetVar( $this->mDateFormat, $x ); }
3968 function setEditSection( $x ) { return wfSetVar( $this->mEditSection, $x ); }
3969 function setNumberHeadings( $x ) { return wfSetVar( $this->mNumberHeadings, $x ); }
3970 function setAllowSpecialInclusion( $x ) { return wfSetVar( $this->mAllowSpecialInclusion, $x ); }
3971 function setTidy( $x ) { return wfSetVar( $this->mTidy, $x); }
3972 function setSkin( &$x ) { $this->mSkin =& $x; }
3973
3974 function ParserOptions() {
3975 global $wgUser;
3976 $this->initialiseFromUser( $wgUser );
3977 }
3978
3979 /**
3980 * Get parser options
3981 * @static
3982 */
3983 function newFromUser( &$user ) {
3984 $popts = new ParserOptions;
3985 $popts->initialiseFromUser( $user );
3986 return $popts;
3987 }
3988
3989 /** Get user options */
3990 function initialiseFromUser( &$userInput ) {
3991 global $wgUseTeX, $wgUseDynamicDates, $wgInterwikiMagic, $wgAllowExternalImages,
3992 $wgAllowExternalImagesFrom, $wgAllowSpecialInclusion;
3993 $fname = 'ParserOptions::initialiseFromUser';
3994 wfProfileIn( $fname );
3995 if ( !$userInput ) {
3996 $user = new User;
3997 $user->setLoaded( true );
3998 } else {
3999 $user =& $userInput;
4000 }
4001
4002 $this->mUseTeX = $wgUseTeX;
4003 $this->mUseDynamicDates = $wgUseDynamicDates;
4004 $this->mInterwikiMagic = $wgInterwikiMagic;
4005 $this->mAllowExternalImages = $wgAllowExternalImages;
4006 $this->mAllowExternalImagesFrom = $wgAllowExternalImagesFrom;
4007 wfProfileIn( $fname.'-skin' );
4008 $this->mSkin =& $user->getSkin();
4009 wfProfileOut( $fname.'-skin' );
4010 $this->mDateFormat = $user->getOption( 'date' );
4011 $this->mEditSection = true;
4012 $this->mNumberHeadings = $user->getOption( 'numberheadings' );
4013 $this->mAllowSpecialInclusion = $wgAllowSpecialInclusion;
4014 $this->mTidy = false;
4015 wfProfileOut( $fname );
4016 }
4017 }
4018
4019 /**
4020 * Callback function used by Parser::replaceLinkHolders()
4021 * to substitute link placeholders.
4022 */
4023 function &wfOutputReplaceMatches( $matches ) {
4024 global $wgOutputReplace;
4025 return $wgOutputReplace[$matches[1]];
4026 }
4027
4028 /**
4029 * Return the total number of articles
4030 */
4031 function wfNumberOfArticles() {
4032 global $wgNumberOfArticles;
4033
4034 wfLoadSiteStats();
4035 return $wgNumberOfArticles;
4036 }
4037
4038 /**
4039 * Return the number of files
4040 */
4041 function wfNumberOfFiles() {
4042 $fname = 'Parser::wfNumberOfFiles';
4043
4044 wfProfileIn( $fname );
4045 $dbr =& wfGetDB( DB_SLAVE );
4046 $res = $dbr->selectField('image', 'COUNT(*)', array(), $fname );
4047 wfProfileOut( $fname );
4048
4049 return $res;
4050 }
4051
4052 /**
4053 * Get various statistics from the database
4054 * @access private
4055 */
4056 function wfLoadSiteStats() {
4057 global $wgNumberOfArticles, $wgTotalViews, $wgTotalEdits;
4058 $fname = 'wfLoadSiteStats';
4059
4060 if ( -1 != $wgNumberOfArticles ) return;
4061 $dbr =& wfGetDB( DB_SLAVE );
4062 $s = $dbr->selectRow( 'site_stats',
4063 array( 'ss_total_views', 'ss_total_edits', 'ss_good_articles' ),
4064 array( 'ss_row_id' => 1 ), $fname
4065 );
4066
4067 if ( $s === false ) {
4068 return;
4069 } else {
4070 $wgTotalViews = $s->ss_total_views;
4071 $wgTotalEdits = $s->ss_total_edits;
4072 $wgNumberOfArticles = $s->ss_good_articles;
4073 }
4074 }
4075
4076 /**
4077 * Escape html tags
4078 * Basically replacing " > and < with HTML entities ( &quot;, &gt;, &lt;)
4079 *
4080 * @param string $in Text that might contain HTML tags
4081 * @return string Escaped string
4082 */
4083 function wfEscapeHTMLTagsOnly( $in ) {
4084 return str_replace(
4085 array( '"', '>', '<' ),
4086 array( '&quot;', '&gt;', '&lt;' ),
4087 $in );
4088 }
4089
4090 ?>